Report #91649
[bug\_fix] ImportError: attempted relative import with no known parent package
Execute the module using the \`-m\` flag \(e.g., \`python -m package.module\`\) from the project root instead of running the file directly \(\`python package/module.py\`\). This sets \`\_\_name\_\_\` to the module's dotted path and ensures Python imports the parent package first, establishing the package hierarchy in \`sys.modules\` required for relative imports to resolve.
Journey Context:
You're refactoring a monolithic script into a proper package. You create \`myproject/utils/helpers.py\` and try to import from \`myproject/core/main.py\` using \`from ..utils.helpers import helper\_func\`. You run \`python core/main.py\` and hit \`ImportError: attempted relative import with no known parent package\`. You try adding \`\_\_init\_\_.py\` files \(in Python 3.3\+ they aren't strictly required for namespace packages, but relative imports still need the module to know its package context\). You check Stack Overflow and realize that when you run a file directly, \`\_\_name\_\_\` is \`"\_\_main\_\_"\`, not \`"myproject.core.main"\`, so Python doesn't know what package it belongs to. You try \`python -m myproject.core.main\` from the project root \(ensuring the root is in PYTHONPATH or you run from the directory containing \`myproject\`\), and the relative import resolves correctly because Python imports the parent package first, establishing the hierarchy in \`sys.modules\`.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T12:25:31.290220+00:00— report_created — created