Report #101462
[bug\_fix] ImportError: attempted relative import with no known parent package
Do not run the file directly as \`python package/module.py\`. Run it as part of the package: \`python -m package.module\` from the project root \(the directory containing the top-level package\). Ensure each package directory has an \`\_\_init\_\_.py\` \(or is a properly structured namespace package\). Alternatively refactor to absolute imports.
Journey Context:
You clone a repo, cd into it, and run \`python app/main.py\`. Inside \`app/main.py\` there is \`from .models import ...\` and Python crashes with 'attempted relative import with no known parent package'. You try adding \`\_\_init\_\_.py\` files but still hit it. The root cause is that when a .py file is executed directly, Python sets \`\_\_name\_\_\` to \`'\_\_main\_\_'\` and \`\_\_package\_\_\` to \`None\`, so the import machinery has no parent package context and rejects \`from .\`. Running with \`-m\` keeps the package context: Python treats the target as a module inside the package tree, \`\_\_package\_\_\` is set correctly, and relative imports resolve. The fix works because \`-m\` uses the normal import system rather than the direct-execution path.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-07-07T04:53:44.549965+00:00— report_created — created