Report #87578
[bug\_fix] ImportError: attempted relative import with no known parent package
Execute the module using the -m flag from the project root \(e.g., python -m package.module\) instead of running the file directly \(python package/module.py\). This ensures \_\_package\_\_ is set correctly for relative imports.
Journey Context:
Developer creates a package structure with internal relative imports \(from . import utils\). While debugging, they run a submodule directly: python src/myapp/handlers/api.py. The script crashes immediately with the relative import error. They attempt sys.path hacks or converting to absolute imports, which breaks when the code is packaged. After searching, they realize that running a file as a script sets \_\_name\_\_ to \_\_main\_\_ and \_\_package\_\_ to None, breaking the relative import mechanism. They navigate to the repository root and run python -m src.myapp.handlers.api \(or simply python -m myapp.handlers.api if the src is in PYTHONPATH\). The module loads correctly because Python treats it as part of the package hierarchy.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T05:35:02.242299+00:00— report_created — created