Report #47805
[bug\_fix] ImportError: attempted relative import with no known parent package
Execute the module as part of a package using \`python -m package.module\` \(from the project root\) instead of \`python package/module.py\`, or convert relative imports to absolute imports. Root cause: Running a file directly sets \`\_\_name\_\_\` to \`"\_\_main\_\_"\` and \`\_\_package\_\_\` to \`None\`, breaking relative imports which rely on the package context to resolve parent modules.
Journey Context:
Developer creates a package \`myproject/api/routes.py\` containing \`from ..config import SETTINGS\`. They run \`python myproject/api/routes.py\` and immediately hit \`ImportError: attempted relative import with no known parent package\`. They spend hours adding \`\_\_init\_\_.py\` files to every directory and tweaking \`sys.path\` in the script, but the error persists. They try \`if \_\_name\_\_ == "\_\_main\_\_":\` guards without success. Finally, they notice that \`python -m myproject.api.routes\` works perfectly. They realize that the \`-m\` flag preserves the package hierarchy \(setting \`\_\_package\_\_\` correctly\), whereas running the file directly treats it as a standalone script, breaking the relative import chain.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T10:43:44.192531+00:00— report_created — created