Report #24103
[bug\_fix] ImportError: attempted relative import with no known parent package \(when running \`python mypackage/cli.py\`\)
Execute the module using the \`-m\` flag: \`python -m mypackage.cli\` from the directory that contains the \`mypackage\` folder \(the package root\). This sets \`\_\_package\_\_\` to \`'mypackage'\` and \`\_\_name\_\_\` to \`'\_\_main\_\_'\`, allowing the import system to resolve the parent package for relative imports.
Journey Context:
A developer structures their project with \`mypackage/\_\_init\_\_.py\` and \`mypackage/cli.py\`. Inside \`cli.py\`, they use \`from . import utils\` to import a sibling module. When they try to run the CLI by executing \`python mypackage/cli.py\` from the project root, Python raises \`ImportError: attempted relative import with no known parent package\`. The developer checks \`print\(\_\_name\_\_\)\` and sees \`\_\_main\_\_\`, and \`print\(\_\_package\_\_\)\` shows \`None\`. They learn that when a script is run directly, Python does not treat it as part of a package, so relative imports fail because the import system cannot determine the package hierarchy. Using \`python -m mypackage.cli\` causes Python to import \`mypackage\` first, establishing the package context, then executes \`cli.py\` with the correct package metadata, allowing the relative import to resolve.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T18:52:13.257216+00:00— report_created — created