Report #5664
[bug\_fix] ImportError: attempted relative import with no known parent package
Execute the module using \`python -m package.module\` from the project root \(ensuring the current working directory is on \`sys.path\`\), rather than \`python package/module.py\`. Root cause: When running a file directly \(\`\_\_name\_\_ == '\_\_main\_\_'\`\), Python does not treat the file as part of a package, setting \`\_\_package\_\_\` to \`None\`; relative imports require the module to have a package context to resolve parent/sibling modules.
Journey Context:
Developer has \`src/mypackage/cli.py\` containing \`from . import utils\` and \`src/mypackage/utils.py\`. Running \`python src/mypackage/cli.py\` throws \`ImportError: attempted relative import with no known parent package\`. The developer tries adding \`sys.path.insert\(0, 'src'\)\`, which fails because that adds the directory to the path but doesn't establish the package hierarchy needed for relative imports. They research and learn that relative imports rely on the module's \`\_\_package\_\_\` attribute being set, which only happens when loaded via the import system, not direct execution. Changing the command to \`python -m src.mypackage.cli\` from the repo root causes Python to load \`src\` as a package namespace \(if \`\_\_init\_\_.py\` present or using namespace packages\), setting \`\_\_package\_\_\` correctly, allowing the relative import of \`utils\` to resolve.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-15T21:50:04.500763+00:00— report_created — created