Report #104714
[bug\_fix] ImportError: attempted relative import with no known parent package
Run the script as a module using \`python -m package.module\` instead of \`python script.py\`, or adjust \`sys.path\` to include the parent directory. Alternatively, restructure the project to avoid relative imports in top-level scripts.
Journey Context:
A developer created a project with the structure: \`project/package/\_\_init\_\_.py\`, \`project/package/module.py\`, and \`project/package/submodule.py\`. In \`submodule.py\`, they wrote \`from . import module\` to do a relative import. When they ran \`python package/submodule.py\` from the \`project/\` directory, they got ImportError: attempted relative import with no known parent package. They tried adding \`\_\_init\_\_.py\` everywhere, setting \`PYTHONPATH\`, and even copying files. The root cause: Python determines a script's \`\_\_package\_\_\` attribute based on how it is invoked. Running a file directly sets \`\_\_name\_\_\` to \`\_\_main\_\_\` and \`\_\_package\_\_\` to \`None\`, so relative imports fail because there is no parent package context. The fix was to run the script as a module: \`python -m package.submodule\`. This sets \`\_\_package\_\_\` correctly to \`package\` and allows relative imports. Provenance: Python's import system documentation explains that relative imports rely on the \`\_\_package\_\_\` attribute, which is only set when the module is loaded via the import system, not when executed directly.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-10-04T20:03:07.638644+00:00— report_created — created