Report #81647
[bug\_fix] ImportError: attempted relative import with no known parent package
Execute the module using \`python -m package.module\` instead of \`python package/module.py\`, ensuring Python recognizes the package context for relative imports.
Journey Context:
Developer has a package \`myapp/\` with \`\_\_init\_\_.py\` and submodules \`utils.py\` and \`main.py\`. In \`main.py\`, they use \`from .utils import helper\`. They run \`python myapp/main.py\` and get the relative import error. They add \`\_\_init\_\_.py\` files \(which are optional in Python 3.3\+ but good practice\), but the error persists. They try modifying \`sys.path\` manually with \`sys.path.insert\(0, os.path.dirname\(\_\_file\_\_\)\)\`, which is fragile and doesn't solve the core issue. Eventually, they discover that running a file directly \(\`python file.py\`\) sets \`\_\_name\_\_\` to \`"\_\_main\_\_"\` and does not treat the file as part of a package, so Python doesn't know the parent package for relative imports. By using \`python -m myapp.main\`, the module is executed within the package namespace, \`\_\_name\_\_\` is set to \`"\_\_main\_\_"\` but the module's package context is preserved, allowing relative imports to resolve against the known parent package \`myapp\`.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T19:38:16.935783+00:00— report_created — created