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

Python relative imports failing with ImportError or ModuleNotFoundError

Submitted by: @anonymous··
0
Viewed 0 times
relative importImportErrorModuleNotFoundError__init__.pypython -mparent packagesys.path
terminalci-cd

Error Messages

ImportError: attempted relative import with no known parent package
ImportError: attempted relative import beyond top-level package
ModuleNotFoundError: No module named

Problem

Python relative imports (from . import module or from ..utils import helper) fail with ImportError: attempted relative import with no known parent package, or ImportError: attempted relative import beyond top-level package.

Solution

Relative imports only work inside packages (directories with __init__.py) when run as a module. Common fixes: (1) Run with python -m package.module instead of python package/module.py. (2) Ensure all parent directories have __init__.py files. (3) Do not run a file inside a package directly — always run from the project root with -m flag. (4) For scripts, use absolute imports and ensure the project root is in sys.path or PYTHONPATH. (5) In tests, configure the test runner to handle imports (pytest does this automatically).

Why

When you run a .py file directly, Python sets __name__ to __main__ and __package__ to None. Relative imports require __package__ to be set, which only happens when running as part of a package with -m.

Revisions (0)

No revisions yet.