Report #15125
[bug\_fix] ImportError: attempted relative import with no known parent package
Run the module using \`python -m package.submodule\` from the project root instead of \`python package/submodule.py\`, or convert the relative imports to absolute imports using the package name. Using \`-m\` executes the module with \`\_\_package\_\_\` correctly set, allowing Python to resolve the relative import's anchor point.
Journey Context:
You have a project with \`myapp/models.py\` containing \`from .database import db\`. You run \`python myapp/models.py\` directly and immediately hit \`ImportError: attempted relative import with no known parent package\`. You try adding an \`\_\_init\_\_.py\` to every directory, but the error persists. You search online and find conflicting advice about using \`if \_\_name\_\_ == '\_\_main\_\_':\` blocks. Eventually, you realize that when you run a file directly, Python sets \`\_\_name\_\_\` to \`'\_\_main\_\_'\` and \`\_\_package\_\_\` to \`None\`, breaking the relative import's reference frame. By changing your execution command to \`python -m myapp.models\` from the parent directory, Python treats \`myapp\` as the package root, sets \`\_\_package\_\_\` correctly, and the relative import resolves against the package hierarchy rather than the file location.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T23:16:33.561476+00:00— report_created — created