Report #21644
[bug\_fix] ImportError: attempted relative import with no known parent package
Execute the module as part of a package using \`python -m package.submodule\` from the parent directory, rather than running the file directly as a script with \`python package/submodule.py\`.
Journey Context:
A developer is refactoring a flat script into a proper package structure with \`myapp/\_\_init\_\_.py\`, \`myapp/main.py\`, and \`myapp/utils.py\`. In \`main.py\`, they add \`from . import utils\` to use a helper function. When they attempt to test the code by running \`python myapp/main.py\`, the interpreter throws \`ImportError: attempted relative import with no known parent package\`. The developer tries moving \`\_\_init\_\_.py\` to parent directories, adding \`sys.path.insert\(0, os.path.dirname\(...\)\)\` hacks, and using \`if \_\_name\_\_ == '\_\_main\_\_':\` guards, but the error persists. The debugging revelation comes when they learn that when a file is executed as a script \(\`python foo.py\`\), Python sets \`\_\_name\_\_\` to \`"\_\_main\_\_"\` and crucially sets \`\_\_package\_\_\` to \`None\`. Relative imports rely on \`\_\_package\_\_\` being set to the package name to resolve the dot notation. The fix works because \`python -m myapp.main\` \(executed from the project root\) treats the code as a module import, not a script execution. This sets up the proper package context, setting \`\_\_package\_\_\` to \`myapp\`, allowing relative imports to resolve correctly.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T14:44:45.046045+00:00— report_created — created