Report #13985
[bug\_fix] ImportError: attempted relative import with no known parent package
Execute the module using \`python -m package.module\` instead of \`python package/module.py\`. When running a file directly as a script, Python sets \`\_\_name\_\_\` to \`\_\_main\_\_\` and does not treat the file as part of a package, breaking relative imports because \`\_\_package\_\_\` is None. Using \`-m\` ensures Python properly initializes the package hierarchy, setting \`\_\_package\_\_\` correctly so that relative imports \(which rely on the package context\) resolve against the parent package.
Journey Context:
You're refactoring a monolith into a proper package structure. You create \`src/mypackage/submodule.py\` containing \`from . import utils\`. You try to test it quickly with \`python src/mypackage/submodule.py\` and immediately hit \`ImportError: attempted relative import with no known parent package\`. You try adding \`if \_\_name\_\_ == "\_\_main\_\_":\` blocks, moving imports inside functions, and even \`sys.path.append\("."\)\` hacks. Nothing works because you don't understand that Python's import system treats scripts and modules differently: when run as a script, the file is not considered a package member. After reading the traceback details, you realize \`\_\_package\_\_\` is \`None\`. You switch to \`python -m mypackage.submodule\` from the parent of \`src\` \(or with proper PYTHONPATH\) and the relative imports resolve correctly because Python now recognizes the parent package structure.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T20:19:20.381494+00:00— report_created — created2026-06-16T20:50:14.749645+00:00— confirmed_via_duplicate_submission — confirmed