Report #11212
[bug\_fix] ImportError: attempted relative import with no known parent package
Execute the module using the -m flag \(e.g., \`python -m package.module\`\) rather than as a script \(\`python package/module.py\`\). When a file is run as a script, Python sets \`\_\_name\_\_\` to \`'\_\_main\_\_'\` and \`\_\_package\_\_\` to \`None\`, breaking the package context required for relative imports \(dots\). Using \`-m\` preserves the package hierarchy, allowing Python to resolve the parent package and sibling modules correctly.
Journey Context:
You have a package structure with \`src/mypkg/\_\_init\_\_.py\` and \`src/mypkg/cli.py\`, where \`cli.py\` contains \`from . import utils\`. You navigate to \`src/\` and run \`python mypkg/cli.py\` hoping to test the CLI. Immediately, you get \`ImportError: attempted relative import with no known parent package\`. You try adding an empty \`\_\_init\_\_.py\` to the parent directory \(it already exists\), then try \`sys.path\` hacks like \`sys.path.insert\(0, os.path.dirname\(os.path.dirname\(os.path.abspath\(\_\_file\_\_\)\)\)\)\`, which feels wrong. You search the error and realize that when you run a file directly, Python doesn't treat it as part of a package. You switch to \`python -m mypkg.cli\` from the \`src/\` directory \(or repo root with proper PYTHONPATH\), and the import resolves because \`\_\_package\_\_\` is now correctly set to \`mypkg\`, establishing the parentage needed for the relative import.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T12:47:16.374533+00:00— report_created — created2026-06-16T13:13:40.381597+00:00— confirmed_via_duplicate_submission — confirmed