Report #66380
[bug\_fix] ImportError: attempted relative import with no known parent package
Run the module using 'python -m package.module' from the project root \(where 'package' is importable\), rather than 'python package/module.py'. Alternatively, restructure to use absolute imports. The root cause is that when a script is executed directly \('python foo/bar.py'\), Python sets '\_\_name\_\_' to '\_\_main\_\_' and '\_\_package\_\_' to 'None', breaking relative imports which rely on '\_\_package\_\_' to resolve parent packages. Using '-m' ensures the module is imported through the import system with proper package context.
Journey Context:
Developer has a project structure: 'myproject/mypkg/\_\_init\_\_.py' and 'myproject/mypkg/utils.py'. 'utils.py' contains 'from . import config' \(relative import\). Developer navigates to 'myproject/' and runs 'python mypkg/utils.py' to test it. Immediately gets 'ImportError: attempted relative import with no known parent package'. Developer tries adding 'sys.path.insert\(0, os.path.dirname\(os.path.abspath\(\_\_file\_\_\)\)\)' at the top, which doesn't help. They try 'from mypkg import config' \(absolute\) which fails with ModuleNotFoundError because 'mypkg' isn't in PYTHONPATH when run as script. Finally, running 'python -m mypkg.utils' from the parent directory works because Python treats it as a module within the 'mypkg' package.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T17:53:44.219374+00:00— report_created — created