Report #20831
[bug\_fix] ImportError: attempted relative import with no known parent package
Run the module as part of a package using 'python -m package.module' instead of 'python package/module.py', ensuring sys.argv\[0\] is a module name that Python can resolve within the package namespace.
Journey Context:
You have a project with 'src/mypkg/\_\_init\_\_.py' and 'src/mypkg/submod.py' which contains 'from . import something'. You run 'python src/mypkg/submod.py' directly to test it, and immediately get 'ImportError: attempted relative import with no known parent package'. You try adding the parent directory to PYTHONPATH with 'export PYTHONPATH=src', but the error persists. You search StackOverflow and see conflicting advice about using 'if \_\_name\_\_ == "\_\_main\_\_":' blocks or converting to absolute imports. Eventually you realize that when you run a file directly as 'python path/to/file.py', Python sets \_\_name\_\_ to '\_\_main\_\_' and does not treat the file as part of a package, so relative imports have no parent package context to resolve against. By changing your execution command to 'python -m mypkg.submod' from the 'src' directory \(or using 'python -m mypkg.submod' with proper PYTHONPATH\), Python treats the file as a module within the mypkg package, \_\_name\_\_ becomes 'mypkg.submod', and relative imports resolve correctly against the package hierarchy.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T13:22:33.824689+00:00— report_created — created