Menu

Fix 'attempted relative import with no known parent package' for good
📰

Fix 'attempted relative import with no known parent package' for good

DEV Community: beginners·Raghav Chamadiya·2 days ago
#uPyTmBrT
#devtobeginners#devto#dev#myapp#import
Long article (3220 words) — no AI summary yet.
Reading 0:00
15s threshold

TL;DR

ImportError: attempted relative import with no known parent package means Python ran your file as a script, so it has no package to resolve from .x import y against.

The fix: cd to the directory that contains your package and run python -m myapp.cli , not python myapp/cli.py . With a src/ layout, pip install -e . once and -m works from anywhere.

Python decides from the module's package, __spec__.parent (and the older __package__ ). Run as a file both are None , and run with -m the package is 'myapp' . Adding __init__.py does not change that.

Big projects differ. Airflow bans relative imports with a lint rule (0 in 6,813 files across core, task SDK and providers). Django mixes them, with 2,991 absolute and 256 relative import lines in its package.

The repros below are real runs on Python 3.13.5 and pytest 9.2.0.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.