Report #96650
[bug\_fix] ImportError: attempted relative import with no known parent package
Execute the module using the -m flag from the project root: \`python -m package.submodule\` instead of \`python package/submodule.py\`. This preserves the package context by setting \_\_name\_\_ to the fully qualified module name and \_\_package\_\_ appropriately, allowing Python to resolve relative imports \(e.g., \`from . import foo\`\) by traversing the package hierarchy rather than treating the file as a standalone script.
Journey Context:
A developer clones a repository with a standard package structure: \`myproject/mypackage/module.py\` containing \`from . import utils\`. They navigate into \`mypackage\` and run \`python module.py\` to test a quick change. It crashes with the relative import error. They try adding empty \`\_\_init\_\_.py\` files \(which exist\), then add \`sys.path.insert\(0, '..'\)\` hacks, then try \`if \_\_name\_\_ == '\_\_main\_\_': import utils\` absolute imports, breaking the package structure. Eventually they realize that running a file directly sets \`\_\_name\_\_\` to \`'\_\_main\_\_'\` and \`\_\_package\_\_\` to \`None\`, so Python cannot determine the relative import's parent package. Using \`python -m mypackage.module\` from the project root runs the same code but within the package context, fixing the import resolution.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T20:48:43.568733+00:00— report_created — created