Report #7964
[bug\_fix] ImportError: attempted relative import with no known parent package
Execute the module using the package syntax \`python -m package.module\` instead of \`python package/module.py\`, ensuring the parent package is importable \(e.g., via \`pip install -e .\` for src-layouts\).
Journey Context:
Developer executes \`python src/myapp/utils/helper.py\` directly. Python sets \`\_\_name\_\_\` to \`"\_\_main\_\_"\` and \`\_\_package\_\_\` to \`None\`, causing any \`from . import config\` to fail because the import system cannot determine the package hierarchy without the parent package being imported first. Developer tries hacks like \`sys.path.insert\(0, os.path.dirname\(...\)\)\` or \`if \_\_name\_\_ == '\_\_main\_\_': from . import config\`, which fail or cause double-import issues. Deep dive into PEP 366 and the import system reveals that \`\_\_main\_\_\` modules have no package context. Switching to \`python -m src.myapp.utils.helper\` \(with \`src\` added to PYTHONPATH or installed editable\) sets \`\_\_package\_\_\` correctly, allowing relative imports to resolve against the known parent package.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T04:14:32.414338+00:00— report_created — created