Report #9680
[bug\_fix] ImportError: attempted relative import with no known parent package
Execute the module using the '-m' flag: 'python -m package.submodule' instead of 'python package/submodule.py'. Root cause: Direct execution sets \_\_name\_\_ to '\_\_main\_\_', breaking the package context required for relative imports \(dots\). The '-m' flag runs the module within the package namespace, preserving parent references and allowing relative imports to resolve.
Journey Context:
You are working on a project with 'src/mypackage/utils/helper.py' that contains 'from ..core import config'. You run 'python src/mypackage/utils/helper.py' and immediately hit 'ImportError: attempted relative import with no known parent package'. You add \_\_init\_\_.py files to every directory, but the error persists. You print \_\_name\_\_ inside the script and see '\_\_main\_\_' instead of 'mypackage.utils.helper'. Checking sys.path, you see the script's directory added, not the package root. You realize that direct execution strips package context. You change your command to 'cd src && python -m mypackage.utils.helper'. The relative import now works because Python treats it as a module within the mypackage namespace, establishing the parent package context needed for the dot notation.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T08:47:19.449563+00:00— report_created — created