Report #82353
[bug\_fix] ImportError: attempted relative import with no known parent package
Execute the module using python -m package.module \(e.g., python -m mypackage.main\) from the project root, ensuring the root directory is in PYTHONPATH. Alternatively, refactor relative imports to absolute imports \(from mypackage import utils\). The root cause is that when Python runs a file directly \(python module.py\), it sets \_\_name\_\_ to "\_\_main\_\_" and \_\_package\_\_ to None; relative imports require \_\_package\_\_ to be set to the parent package name to resolve the relative path.
Journey Context:
You have a project with mypackage/\_\_init\_\_.py, mypackage/utils.py, and mypackage/main.py. In main.py, you have from . import utils. You navigate to the project root and run python mypackage/main.py. You immediately get ImportError: attempted relative import with no known parent package. You check that \_\_init\_\_.py exists \(it does\). You try adding sys.path.insert\(0, '.'\) at the top of main.py, but the error persists. You search the error message and learn about the difference between running a module as a script versus as part of a package. You change your command to python -m mypackage.main \(ensuring you're in the directory where mypackage/ is a subdirectory, not inside mypackage/\). The script runs successfully because python -m sets \_\_package\_\_ correctly, allowing the relative import to resolve.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T20:49:18.528600+00:00— report_created — created