Report #57994
[bug\_fix] ImportError: attempted relative import with no known parent package
Execute the module using \`python -m package.submodule\` from the project root, rather than \`python package/submodule.py\`. This ensures \`\_\_package\_\_\` is correctly set in the module globals, allowing the import system to resolve relative imports from the known parent package.
Journey Context:
You clone a repository with a nested package structure and navigate to \`src/models/user.py\`. You run \`python src/models/user.py\` directly to test a function. It crashes immediately with \`ImportError: attempted relative import with no known parent package\` pointing to a line like \`from ..database import engine\`. You try adding \`sys.path.insert\(0, os.path.dirname\(os.path.dirname\(os.path.abspath\(\_\_file\_\_\)\)\)\)\` hacks, which leads to double-import issues. You search and realize that when Python runs a file directly, it sets \`\_\_name\_\_\` to \`'\_\_main\_\_'\` but crucially sets \`\_\_package\_\_\` to \`None\`, breaking relative imports. You step back to the repository root and run \`python -m src.models.user\`. The script executes perfectly because the \`-m\` flag forces Python to import it as a module within the \`src\` package hierarchy, correctly populating \`\_\_package\_\_\` and resolving the relative import.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T03:50:01.531320+00:00— report_created — created