Report #84942
[bug\_fix] ImportError: attempted relative import with no known parent package
Execute the module using the -m flag \(e.g., \`python -m mypackage.module\`\) from the project root directory, ensuring the parent directory is in Python's path and \_\_name\_\_ is set to the full dotted path, not \_\_main\_\_. Alternatively, install the package in editable mode \(\`pip install -e .\`\) and refactor relative imports to absolute imports.
Journey Context:
A developer is working on a package with internal relative imports \(e.g., \`from . import utils\` inside \`mypackage/main.py\`\). To test a quick change, they run the script directly via \`python mypackage/main.py\` from the project root. Immediately, a traceback appears with \`ImportError: attempted relative import with no known parent package\`. The developer verifies that \`\_\_init\_\_.py\` files exist in all directories. They try adding the current directory to \`PYTHONPATH\` with \`PYTHONPATH=. python mypackage/main.py\`, which still fails. They then realize that when a script is run directly, Python sets \`\_\_name\_\_\` to \`"\_\_main\_\_"\` and does not treat the file as part of a package, making relative imports impossible. Switching to \`python -m mypackage.main\` from the parent directory fixes the issue because Python properly establishes the package context, setting \`\_\_name\_\_\` to \`"mypackage.main"\` and 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-22T01:09:49.161606+00:00— report_created — created