Report #95075
[bug\_fix] ImportError: attempted relative import with no known parent package
Run the module using the -m flag \(e.g., python -m package.module\) instead of running the file directly \(python package/module.py\), or convert relative imports to absolute imports.
Journey Context:
Developer refactors a flat project into a package with submodules, adding \_\_init\_\_.py files and converting imports to relative \(from .utils import helper\). They try to quickly test a submodule by running python mypkg/cli.py from the project root. It crashes with 'attempted relative import with no known parent package'. They try adding the parent directory to sys.path manually, changing dots to absolute imports \(which works but breaks the package structure when installed\), and checking \_\_package\_\_ attribute. They realize that when a file is run as a script \(\_\_name\_\_ == '\_\_main\_\_'\), Python does not treat it as part of a package, so relative imports have no parent context. Using python -m mypkg.cli executes the module with proper package context, setting \_\_package\_\_ correctly, allowing the relative imports to resolve.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T18:09:50.290028+00:00— report_created — created