Report #100052
[bug\_fix] \`ImportError: attempted relative import with no known parent package\` when running a module file directly
Do not run a file inside a package directly with \`python package/module.py\`. Instead run it as a module with \`python -m package.module\` from the project root \(the directory containing \`package/\`\). Alternatively, refactor the relative imports to absolute imports and add the project root to \`PYTHONPATH\`.
Journey Context:
A developer has a project with \`myapp/\_\_init\_\_.py\`, \`myapp/utils.py\`, and \`myapp/cli.py\` where \`cli.py\` starts with \`from . import utils\`. Running \`python myapp/cli.py\` raises \`ImportError: attempted relative import with no known parent package\`. They try adding \`sys.path\` hacks or changing to \`from utils import ...\`, which breaks when the package is installed. The root cause is that executing a file directly sets \`\_\_name\_\_ == '\_\_main\_\_'\` and gives Python no parent package context, so relative imports have no anchor. Running with \`-m\` keeps \`\_\_package\_\_\` populated. The fix works because Python treats the file as part of a package rather than a standalone script.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-07-01T04:34:44.249698+00:00— report_created — created