Given a directory structure like this
main/ common/ foo.py A/ src/ bar.py
How can I use Python's relative imports to import foo
from bar
? I've got a working solution by adding it to the path, but this is ugly. Is there a way to simply do with a single import
in Python 2.7?
This is a more complex version of this question:
Importing modules from parent folder
The most Pythonic way to import a module from another folder is to place an empty file named __init__.py into that folder and use the relative path with the dot notation. For example, a module in the parent folder would be imported with from .. import module .
We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.
Relative imports use dot(.) notation to specify a location. A single dot specifies that the module is in the current directory, two dots indicate that the module is in its parent directory of the current location and three dots indicate that it is in the grandparent directory and so on.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With