Report #68853
[bug\_fix] ImportError: attempted relative import with no known parent package
Run the module using \`python -m package.submodule\` instead of \`python package/submodule.py\`. The root cause is that when you run a file directly as a script \(\`python file.py\`\), Python sets \`\_\_name\_\_\` to \`'\_\_main\_\_'\` and does not treat it as part of a package, so relative imports \(dots\) have no parent package context to resolve against. Using \`-m\` executes the module within the package namespace, setting \`\_\_name\_\_\` to \`'package.submodule'\` and establishing the parent package chain.
Journey Context:
Developer has a project structure with \`myapp/utils/helper.py\` trying to do \`from ..config import settings\`. They run \`python myapp/utils/helper.py\` and get the relative import error. They try to fix it by adding \`sys.path.insert\(0, ...\)\` which is messy. They search and learn about the difference between running a script and importing a module. When you run \`python file.py\`, Python puts the file's directory on sys.path and sets \`\_\_name\_\_\` to \`\_\_main\_\_\`, breaking the package context. Using \`python -m myapp.utils.helper\` from the project root \(where \`myapp\` is importable\) preserves the package structure, allowing the relative import dots to resolve correctly up the package tree.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T22:03:19.822458+00:00— report_created — created