Report #77371
[bug\_fix] ImportError: attempted relative import with no known parent package
Run the code as a module using 'python -m package.submodule' from the project root instead of 'python package/submodule.py', ensuring \_\_package\_\_ is set correctly to enable relative imports.
Journey Context:
A developer has a package structure: 'project/src/mypkg/\_\_init\_\_.py', 'project/src/mypkg/utils.py', and 'project/src/mypkg/cli.py'. Inside cli.py, they use 'from . import utils' to import the sibling module. When they run 'python src/mypkg/cli.py' from the project directory, Python raises 'ImportError: attempted relative import with no known parent package'. The developer inspects \_\_name\_\_ \(which is '\_\_main\_\_'\) and \_\_package\_\_ \(which is None\) and realizes that running a file directly causes Python to treat it as a top-level script, not as part of a package, stripping the package context needed for relative imports. They try adding 'sys.path.insert' hacks, which cause other import issues. Eventually, they learn that using 'cd src && python -m mypkg.cli' works because the '-m' flag tells Python to import the module via the import system, which sets \_\_package\_\_ to 'mypkg', allowing the relative import to resolve the parent package correctly.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T12:28:14.230418+00:00— report_created — created