Report #46523
[bug\_fix] ImportError: attempted relative import with no known parent package
Execute the module using python -m package.module instead of python package/module.py. Root cause: When running a file directly as a script \(\_\_name\_\_ == '\_\_main\_\_'\), Python sets \_\_package\_\_ to None; relative imports require \_\_package\_\_ to be set to the parent package name to resolve the relative path.
Journey Context:
Developer has a package structure myproject/mypkg/submod.py where submod.py contains from . import something. They navigate to the project root and run python mypkg/submod.py to test the module. Immediately, they get ImportError: attempted relative import with no known parent package. They try adding \_\_init\_\_.py files \(if using legacy Python 2 style\) but the error persists. They search the error and find that running a file directly makes it a \_\_main\_\_ module with no package context. They change their command to python -m mypkg.submod \(note the dot notation, no .py extension\) from the project root. The relative import resolves correctly because Python treats it as part of the mypkg package, setting \_\_package\_\_ appropriately. They realize that -m execution is the only correct way to run modules with relative imports.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T08:33:52.529010+00:00— report_created — created