Fix "attempted relative import with no known parent package" in Python
ImportError: attempted relative import with no known parent package
- ImportError: attempted relative import beyond top-level package
- ModuleNotFoundError: No module named '__main__.utils'; '__main__' is not a package
- SystemError: Parent module '' not loaded, cannot perform relative import
You are running a file directly (python app/main.py) that contains a relative import such as from .utils import x. Run that way, the file belongs to no package. Run it as a module from the project root with python -m app.main, or switch to absolute imports and install the project with pip install -e ..
What this error means
A relative import (from . import x, from ..config import y) is resolved from __package__, the package the current module belongs to. When you run a file with python path/file.py, Python loads it under the name __main__ and __package__ is empty: there is no parent package, so the dot in from .utils points to nothing. With python -m app.main, Python imports the module as a member of the app package, and the relative import works. The “beyond top-level package” variant appears when .. goes above the highest known package.
Common causes
- Package file run as a script:
python app/main.pyorcd app && python main.pywhilemain.pycontainsfrom .utils import .... - Editor “Run” button: VS Code or PyCharm run the open file as a script, not as a module.
- Relative import in a standalone script: a file at the project root, outside any package, uses
from .x import y. ..going too high: the target module sits above the package run with-m, hence “beyond top-level package”.
Step-by-step fix
-
Check the project structure
Files that import each other must live in a package folder. Add an
__init__.pyfile (even empty): namespace packages work without it, but an explicit package avoids surprises with pytest, mypy and editors.project/ ├── pyproject.toml └── app/ ├── __init__.py ├── main.py # from .utils import slugify └── utils.py -
Run the module with python -m from the root
Go to the folder that contains the package, then pass the module path with dots and without
.py. This is the most direct fix.cd project python -m app.main -
Prefer absolute imports
Absolute imports (
from app.utils import slugify) are easier to read and work from any module in the package. They also require theprojectfolder to be on the import path: always run withpython -mor install the project (next step).# app/main.py from app.utils import slugify def main(): print(slugify("Hello World")) if __name__ == "__main__": main() -
Install the project in editable mode
With a minimal
pyproject.tomlandpip install -e ., the package becomes importable from any folder, tests included. The[project.scripts]entry also creates anappcommand.[build-system] requires = ["setuptools>=64"] build-backend = "setuptools.build_meta" [project] name = "app" version = "0.1.0" [project.scripts] app = "app.main:main" [tool.setuptools] packages = ["app"] # then, in an activated venv: # python -m pip install -e . -
Configure the editor to run a module
In VS Code, use
"module"instead of"program"in.vscode/launch.json. In PyCharm, in the run configuration, switch “Script path” to “Module name” and enterapp.main.{ "version": "0.2.0", "configurations": [ { "name": "app.main", "type": "debugpy", "request": "launch", "module": "app.main", "cwd": "${workspaceFolder}" } ] } -
Fix “beyond top-level package”
If
..targets a module outside the package, run the program from one level higher so that folder becomes the root package, or replace the relative import with an absolute one. Avoid patchingsys.path.append(...): it hides the problem and breaks as soon as the working folder changes.# project/app/api/routes.py # from ...config import settings # beyond top-level package from app.config import settings
Did this fix work for you?
Confirm it in one click: it will rise for the next developers stuck on the same error.
Keep it from coming back
- Adopt a single convention: absolute imports everywhere, project installed with
pip install -e .. - Add an
app/__main__.pyfile so the application can be run withpython -m app. - For pytest, declare the import path with
pythonpath = ["."]in[tool.pytest.ini_options]instead of changingsys.pathin tests.
Frequently asked questions
Do I still need an __init__.py file in Python 3?
It is not mandatory since Python 3.3 (namespace packages, PEP 420), but it is still recommended: it clearly marks the folder as a package and avoids unexpected tool behavior.
Why does python -m app.main work but not python app/main.py?
With -m, Python imports main as a member of the app package, so __package__ is "app". With a file path, the module is called __main__ and has no parent package.
Relative or absolute import: which should I choose?
PEP 8 recommends absolute imports, which are easier to read. Explicit relative imports are still acceptable inside a complex package, as long as those files are never run as scripts.
Useful tools for this error
More Python errors
- Fix "ModuleNotFoundError: No module named" in Python
- Fix "IndentationError: unexpected indent" in Python
- Fix "'NoneType' object is not subscriptable" in Python
- Fix "error: externally-managed-environment" with pip
- Fix "UnicodeDecodeError: 'utf-8' codec can't decode byte" in Python
- Fix "KeyError" in Python (dict, pandas, os.environ)
- Fix "RecursionError: maximum recursion depth exceeded" in Python