Skip to content
Latchkey

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.

python
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 package

Common 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.

Terminal
python -m app.cli

Use absolute imports in entry points

For files run directly, use absolute imports rather than relative ones.

app/cli.py
from app.config import settings  # absolute, works when run directly

How 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.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →