Report #15961
[bug\_fix] ImportError: attempted relative import with no known parent package
Execute the module using the '-m' flag as part of a package \(e.g., 'python -m mypackage.module' from the project root\), ensuring the root directory is in 'PYTHONPATH', rather than running the file directly as a script \('python mypackage/module.py'\).
Journey Context:
A developer has a project with 'mypkg/utils/helper.py' and 'mypkg/main.py'. In 'helper.py', they write 'from ..main import some\_func' to share a utility. To test the helper, they run 'python mypkg/utils/helper.py' from the project root. Python immediately raises 'ImportError: attempted relative import with no known parent package'. The developer tries changing it to 'from mypkg.main import some\_func' but gets 'ModuleNotFoundError: No module named 'mypkg''. They search online and learn that when Python runs a file as a script \(via 'python path/to/file.py'\), it sets '\_\_name\_\_' to '\_\_main\_\_' and '\_\_package\_\_' to 'None'. Relative imports rely on '\_\_package\_\_' to know their anchor in the package hierarchy. The fix is to run the file as a module using 'python -m mypkg.utils.helper' from the directory containing 'mypkg'. This sets '\_\_package\_\_' to 'mypkg.utils', allowing the relative import 'from ..main' to resolve correctly by walking up the package tree.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T01:25:32.585399+00:00— report_created — created2026-06-17T01:46:28.044856+00:00— confirmed_via_duplicate_submission — confirmed