Python "attempted relative import with no known parent package" in CI
A module that uses from . import x was executed directly (e.g. python pkg/mod.py) instead of as part of a package. Without a parent package context, Python cannot resolve the leading dot, so the relative import fails.
What this error means
Running a module directly fails with "ImportError: attempted relative import with no known parent package", while importing it through the package works.
Traceback (most recent call last):
File "app/cli.py", line 3, in <module>
from .config import settings
ImportError: attempted relative import with no known parent packageCommon causes
Running a package module as a script
python app/cli.py runs the file as top-level __main__ with no package, so from .config has no parent to resolve.
A missing __init__.py breaks the package chain
Without __init__.py (under the relevant import mode), the directory is not a package, so relative imports have no parent.
How to fix it
Run it as a module with -m
Invoke through the package so the parent context exists and the dot resolves.
python -m app.cliUse absolute imports in entry points
For files run directly, use absolute imports rather than relative ones.
from app.config import settings # absolute, works when run directlyHow to prevent it
- Run package modules with
python -m package.module. - Use absolute imports in scripts and entry points.
- Define console entry points so the package is invoked correctly.