Relative Imports in Python
In Python, importing modules from within a package can be a tricky task. Consider the following directory structure:
app/ __init__.py sub1/ __init__.py mod1.py sub2/ __init__.py mod2.py
Suppose you're working on mod1.py and need to import something from mod2.py. You might try:
from ..sub2 import mod2
However, this results in an "Attempted relative import in non-package" error. The solution lies in the fact that Python interprets modules run as __main__ (e.g., python mod1.py) as top-level modules, regardless of their file system location.
To enable relative imports, the importing module must not be running as __main__. This can be accomplished by running the interpreter with a package as the main module:
python -m app.sub1.mod1
Alternatively, you can use the __package__ attribute to specify the parent package manually:
import sys sys.path.insert(0, '..') from sub2.mod2 import MyClass
This method manipulates the system path, but it does not require running the module as __main__.
However, for relative imports to work within subpackages, it's important to ensure that __init__.py files are present in each directory. These files act as package markers and enable the __package__ attribute to reference the containing package.
The above is the detailed content of How Can I Successfully Perform Relative Imports in Python Packages?. For more information, please follow other related articles on the PHP Chinese website!