Relative importing modules from parent folder subfolder

后端 未结 1 1610
不思量自难忘°
不思量自难忘° 2020-12-08 13:49

Given a directory structure like this

/main/
/main/common/foo.py
/main/A/
/main/A/src/
/main/A/src/bar.py

How can I use Python\'s relat

相关标签:
1条回答
  • 2020-12-08 14:25

    The correct relative import would be this:

    from ...common import foo
    

    However, relative imports are only meant to work within one package. If main is a package, then you can use relative imports here. If main is not a package, you cannot.

    Thus, if you're running a script in /main/ and doing something like import A.src.bar, then that relative import will fail with "Attempted relative import beyond toplevel package". This is because the relative import is trying to import something outside of the toplevel package A.

    However, if you're running a script in / and doing something like import main.A.src.bar, then that relative import will succeed because main is now a package. In that case, the following two would be equivalent:

    from ...common import foo
    from main.common import foo
    

    To answer your comment: the meaning of the . doesn't change depending on where the script was run from, it changes depending on what the package structure is.

    0 讨论(0)
提交回复
热议问题