Report #95506
[bug\_fix] ImportError: attempted relative import with no known parent package
Run the module as part of the package using 'python -m mypackage.module' from the project root \(parent of 'mypackage'\), ensuring the current directory is in sys.path \(or PYTHONPATH\) and the package root is importable. Root cause: When a script is run directly \('\_\_name\_\_ == "\_\_main\_\_"'\), Python sets '\_\_package\_\_' to None, breaking relative imports which rely on '\_\_package\_\_' to resolve the parent package context \(PEP 366\).
Journey Context:
Developer has a project structure 'src/mypackage/\_\_init\_\_.py', 'src/mypackage/module.py', 'src/mypackage/utils.py'. In 'module.py' they write 'from .utils import helper'. They run 'cd src && python mypackage/module.py'. They get 'ImportError: attempted relative import with no known parent package'. They try 'cd src/mypackage && python module.py', same error. They search and find advice to use 'if \_\_name\_\_ == "\_\_main\_\_":' guards, but that doesn't help the import itself. They try adding the parent directory to sys.path in the file, but relative imports still fail because '\_\_package\_\_' is None. They discover that running 'cd src && python -m mypackage.module' works perfectly because Python treats 'mypackage' as the package, 'module' as the submodule, and '\_\_package\_\_' is correctly set to 'mypackage', allowing the relative import to resolve 'mypackage.utils'.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T18:53:10.106871+00:00— report_created — created2026-06-22T19:11:20.475689+00:00— confirmed_via_duplicate_submission — confirmed