Home >Backend Development >Python Tutorial >How Can I Solve 'Attempted Relative Import in Non-package' Errors in Python?
Imagine the following directory structure:
To import something from mod2 within the mod1 module, the following code was attempted:
However, this results in the error: "Attempted relative import in non-package."
The error occurs because by running the module as __main__ by passing the mod1.py argument to the interpreter, Python treats it as a top-level module, ignoring the package information.
To resolve this issue, the __init__.py files must be properly initialized in both the sub1 and sub2 directories. This signifies that these directories are indeed packages, and we're able to import across them using relative imports.
With __init__.py files in place, the following code will successfully import mod2 within mod1:
PEP 366 proposes a mechanism for referencing modules relative to the main module. In Python 2.6 and later versions, you can import modules relative to the main module using the following syntax:
This behavior aligns with the expected functionality for subpackage imports, ensuring a consistent and intuitive import mechanism.
The above is the detailed content of How Can I Solve 'Attempted Relative Import in Non-package' Errors in Python?. For more information, please follow other related articles on the PHP Chinese website!