Run your entry point as an importable module using python -m package.subpackage.module from the parent directory containing the top-level package instead of executing the file directly by path (python package/subpackage/module.py), and ensure every package folder has an __init__.py file—because running a file directly sets __name__ == "__main__" with __package__ == None (or ""), stripping the package hierarchy Python needs to resolve relative dots (. and ..).
Basic Example
project_root/
└── my_pkg/
├── __init__.py
├── utils.py # defines: def format_name(s): ...
└── subpkg/
├── __init__.py
└── worker.py # imports from parent package: `from ..utils import format_name`
# my_pkg/subpkg/worker.py
from ..utils import format_name
def run() -> None:
print(format_name("alice"))
if __name__ == "__main__":
run()
# ❌ BROKEN: Running directly by file path fails with:
# ImportError: attempted relative import with no known parent package
# (or ModuleNotFoundError: No module named 'my_pkg' when using absolute imports)
cd project_root
python my_pkg/subpkg/worker.py
# ✅ FIXED: Run from `project_root` using `-m` with dotted module path (no `.py` extension):
cd project_root
python -m my_pkg.subpkg.worker
# Output: ALICE
Key Details & Edge Cases
- Why Python raises
ImportErrororModuleNotFoundErrordepending on how you invoke the script:- When you run
python my_pkg/subpkg/worker.py, Python putsproject_root/my_pkg/subpkg(notproject_root) atsys.path[0]and sets__package__toNone. Relative imports (from ..utils import ...) fail because Python has no parent package context, while absolute imports (from my_pkg.utils import ...) raiseModuleNotFoundError: No module named 'my_pkg'becauseproject_rootis not onsys.path. - When you run
python -m my_pkg.subpkg.workerfromproject_root, Python putsproject_rootontosys.path[0], sets__package__ = "my_pkg.subpkg", and resolves both relative (..utils) and absolute (my_pkg.utils) imports cleanly.
- When you run
- Do not traverse above the top-level package (
ValueError: attempted relative import beyond top-level package):- If you invoke
python -m subpkg.workerfrom insidemy_pkg/, thensubpkgbecomes the top-level package, andfrom ..utilsfails because..tries to step abovesubpkg. Always run-mfrom the directory above your root package (project_root).
- If you invoke
- Make your package permanently importable from any directory (
pip install -e .):- For multi-file projects, add a minimal
pyproject.tomlinproject_root/and runpython -m pip install -e .(editable install) inside your virtual environment. Once installed in editable mode,my_pkgis permanently registered onsys.path, so bothpython -m my_pkg.subpkg.workerandpytestwork from any working directory withoutsys.path.append(...)hacks.
- For multi-file projects, add a minimal
- Avoid
sys.path.insert(0, ...)hacks in production code:- Mutating
sys.pathinside modules breaks static type checkers (mypy,pyright), IDE auto-imports, and packaging tools, and can cause duplicate module imports under two different names (utilsvs.my_pkg.utils).
- Mutating
- Switch to explicit absolute imports (
from my_pkg.utils import format_name) for entry-point scripts:- PEP 8 recommends absolute imports as the default; reserve relative imports (
from .helper import x) for intra-package imports between sibling modules inside a library package, and keep entry-point scripts thin (e.g.,main.pyinproject_root/importingmy_pkg).
- PEP 8 recommends absolute imports as the default; reserve relative imports (
Comparison of Fixes for Relative-Import ModuleNotFoundError / ImportError
| Solution | Modifies Source Code? | Works with pytest, IDEs & Type Checkers? |
Works from Any Working Directory? | Best Used When |
|---|---|---|---|---|
python -m my_pkg.subpkg.module (Recommended) |
No | Yes | Only when run from project_root (parent of my_pkg) |
Running any package submodule or CLI entry point directly during development. |
Editable install (pip install -e . with pyproject.toml) (Recommended for projects) |
No (adds pyproject.toml) |
Yes | Yes (from any folder in that venv) | Multi-module packages, test suites (pytest), and reusable libraries. |
Top-level main.py entry script + absolute imports (from my_pkg...) |
Yes (uses absolute imports) | Yes | Yes (when running python main.py) |
Applications where users expect to launch a root script (python main.py). |
sys.path.append(str(Path(__file__).resolve().parents[1])) (Avoid) |
Yes (boilerplate in every file) | No (confuses linters & dual-import state) | Yes | Quick throwaway single-file debugging only—never in shared or packaged code. |
You must log in or register to comment.
