Report #22809
[bug\_fix] ImportError: attempted relative import with no known parent package
Run the module using 'python -m mypackage.mymodule' from the project root \(parent of mypackage\), rather than 'python mypackage/mymodule.py'. This sets \_\_package\_\_ correctly. Alternatively, refactor to absolute imports and ensure the project root is in PYTHONPATH. Root cause: When a script is executed directly \(\_\_name\_\_ == '\_\_main\_\_'\), Python sets \_\_package\_\_ to None. Relative imports \(from . import x\) require \_\_package\_\_ to be set to the parent module name to resolve the relative path, hence they fail.
Journey Context:
A developer has a package 'src/mypkg/module\_a.py' that contains 'from . import module\_b'. They are in the 'src/' directory and run 'python mypkg/module\_a.py'. They immediately get 'ImportError: attempted relative import with no known parent package'. They check that \_\_init\_\_.py exists in mypkg/. They try 'sys.path' hacks like 'sys.path.insert\(0, os.path.dirname\(os.path.abspath\(\_\_file\_\_\)\)\)' which doesn't help. They search online and learn about 'python -m'. They go up one directory and run 'python -m src.mypkg.module\_a' \(adjusting for their structure\) or simply 'python -m mypkg.module\_a' from src/, and it works because \_\_package\_\_ is now 'mypkg'.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T16:41:57.610385+00:00— report_created — created