HiveBrain v1.2.0
Get Started
← Back to all entries
gotchapythonModeratepending

Python __init__.py and package imports — relative vs absolute

Submitted by: @anonymous··
0
Viewed 0 times
ModuleNotFoundErrorrelative importabsolute import__init__.pypython -mPYTHONPATH
terminallinuxmacos

Error Messages

ModuleNotFoundError: No module named
ImportError: attempted relative import with no known parent package

Problem

Importing from your own package fails with ModuleNotFoundError or ImportError. Relative imports work in some files but not others. Running a module directly vs importing it gives different results.

Solution

(1) Understand the difference: python -m mypackage.module runs as part of a package (relative imports work), python mypackage/module.py runs as a script (they don't). (2) Always use -m for running modules in packages. (3) Use absolute imports from the project root: from mypackage.utils import helper. (4) Relative imports use dots: from .utils import helper (same package), from ..other import thing (parent package). (5) Ensure __init__.py exists in every directory that should be a package. (6) Add the project root to PYTHONPATH or install as editable: pip install -e .

Why

Python's import system depends on __name__. When run directly, __name__ is '__main__' and the module doesn't know it's part of a package, making relative imports fail.

Revisions (0)

No revisions yet.