Report #16303
[bug\_fix] ImportError: attempted relative import with no known parent package
Run the module using the \`-m\` flag from the project root \(parent directory of the package\): \`python -m mypackage.submodule\`. Do not run the script directly as \`python mypackage/submodule.py\`. This ensures Python sets \`\_\_package\_\_\` correctly to resolve relative imports.
Journey Context:
Developer has a package structure with \`mypackage/submodule.py\` containing \`from . import utils\`. They attempt to run the script directly with \`python mypackage/submodule.py\`. Python executes the script with \`\_\_name\_\_\` set to \`"\_\_main\_\_"\` and crucially sets \`\_\_package\_\_\` to \`None\`. When the relative import is encountered, Python checks \`\_\_package\_\_\` to determine the parent package context; finding \`None\`, it raises ImportError because it cannot resolve the relative path without knowing the package hierarchy. The developer attempts to fix this by appending parent directories to \`sys.path\`, but this only affects absolute imports, not the relative import logic. The actual fix requires running the module with \`python -m mypackage.submodule\` from the project root \(parent of mypackage\). This execution method sets \`\_\_package\_\_\` to \`"mypackage"\` based on the module path, allowing Python to resolve \`.\` as the parent package \(mypackage\), and \`\_\_name\_\_\` becomes \`"\_\_main\_\_"\` only for the entry point module while preserving the package context for imports.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T02:20:24.820592+00:00— report_created — created