Report #15529
[bug\_fix] ImportError: attempted relative import with no known parent package
Run the module using \`python -m package.module\` from the project root \(with proper PYTHONPATH\) instead of \`python package/module.py\`. When running a file directly, Python sets \`\_\_name\_\_\` to \`"\_\_main\_\_"\` rather than the dotted package path, breaking the parent package context required for relative imports.
Journey Context:
You have a project structure with \`myproject/\` containing \`\_\_init\_\_.py\`, \`utils.py\`, and \`main.py\`. Inside \`main.py\`, you use \`from . import utils\`. You try to test it by running \`python myproject/main.py\` from the parent directory. Immediately, you get \`ImportError: attempted relative import with no known parent package\`. You check that \`\_\_init\_\_.py\` exists—it does. You try adding the parent directory to \`sys.path\` in \`main.py\`, but that doesn't help. You search the error and find PEP 328 discussions. You realize that when you invoke \`python myproject/main.py\`, Python adds \`myproject/\` to \`sys.path\` but treats \`main.py\` as a standalone script \(\`\_\_name\_\_ == "\_\_main\_\_"\`\), not as part of the \`myproject\` package. Therefore, Python cannot determine the parent package for the relative import. You go up one directory and run \`python -m myproject.main\`. The relative import resolves correctly because now \`\_\_package\_\_\` is properly set to \`myproject\`.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T00:21:19.784441+00:00— report_created — created