How do you fix "ModuleNotFoundError" caused by relative imports in Python? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you fix "ModuleNotFoundError" caused by relative imports in Python?

message-square
0

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 ImportError or ModuleNotFoundError depending on how you invoke the script:
    • When you run python my_pkg/subpkg/worker.py, Python puts project_root/my_pkg/subpkg (not project_root) at sys.path[0] and sets __package__ to None. Relative imports (from ..utils import ...) fail because Python has no parent package context, while absolute imports (from my_pkg.utils import ...) raise ModuleNotFoundError: No module named 'my_pkg' because project_root is not on sys.path.
    • When you run python -m my_pkg.subpkg.worker from project_root, Python puts project_root onto sys.path[0], sets __package__ = "my_pkg.subpkg", and resolves both relative (..utils) and absolute (my_pkg.utils) imports cleanly.
  • Do not traverse above the top-level package (ValueError: attempted relative import beyond top-level package):
    • If you invoke python -m subpkg.worker from inside my_pkg/, then subpkg becomes the top-level package, and from ..utils fails because .. tries to step above subpkg. Always run -m from the directory above your root package (project_root).
  • Make your package permanently importable from any directory (pip install -e .):
    • For multi-file projects, add a minimal pyproject.toml in project_root/ and run python -m pip install -e . (editable install) inside your virtual environment. Once installed in editable mode, my_pkg is permanently registered on sys.path, so both python -m my_pkg.subpkg.worker and pytest work from any working directory without sys.path.append(...) hacks.
  • Avoid sys.path.insert(0, ...) hacks in production code:
    • Mutating sys.path inside modules breaks static type checkers (mypy, pyright), IDE auto-imports, and packaging tools, and can cause duplicate module imports under two different names (utils vs. my_pkg.utils).
  • 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.py in project_root/ importing my_pkg).

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.