Report #49978
[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 sets \`\_\_package\_\_\` correctly and allows the import system to resolve relative imports by treating the file as part of a package rather than a standalone script.
Journey Context:
You have a project \`myproject/\` with \`\_\_init\_\_.py\`, \`utils.py\`, and a subpackage \`api/\_\_init\_\_.py\` and \`routes.py\`. Inside \`api/routes.py\` you write \`from .. import utils\` for a relative import. You try to test it by running \`python api/routes.py\` directly from the project root. It crashes with 'ImportError: attempted relative import with no known parent package'. You try adding \`sys.path.insert\(0, os.path.dirname\(os.path.dirname\(os.path.abspath\(\_\_file\_\_\)\)\)\)\` hacks, which sometimes works but breaks when you later try to import \`api.routes\` from elsewhere. You search and learn that when you run a file directly, Python sets \`\_\_name\_\_\` to \`'\_\_main\_\_'\` and \`\_\_package\_\_\` to \`None\`, so relative imports have no anchor point. You change your workflow to run \`python -m api.routes\` from the repository root, and the relative imports resolve correctly because Python treats it as a module load within the \`api\` package.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T14:22:24.067005+00:00— report_created — created