Report #69250
[bug\_fix] ImportError: attempted relative import with no known parent package
Run the module as a package using 'python -m package.module' from the project root, instead of 'python package/module.py'. Root cause: When running a file directly, \_\_name\_\_ is '\_\_main\_\_' and Python treats the file as a top-level script, breaking relative import resolution which requires the module to be part of a package.
Journey Context:
Developer has a project with 'myapp/utils.py' containing 'from . import config'. They run 'python myapp/utils.py' from the terminal. Immediately, ImportError is raised complaining about relative imports. Developer searches the error and finds conflicting advice about modifying sys.path. They try adding 'sys.path.insert\(0, ...\)' but the error persists. They realize that the issue is not path-related but how Python handles the \_\_name\_\_ attribute. When a file is run directly, \_\_name\_\_ is set to '\_\_main\_\_', and Python does not recognize it as being inside the 'myapp' package, so relative imports fail. The developer changes their invocation to 'python -m myapp.utils' from the parent directory. This preserves the package context, \_\_name\_\_ is set to 'myapp.utils', and the relative import resolves correctly.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T22:43:30.548572+00:00— report_created — created