TL;DR

  • ImportError: attempted relative import with no known parent package means Python ran your file as a script, so it has no package to resolve from .x import y against.
  • The fix: cd to the directory that contains your package and run python -m myapp.cli, not python myapp/cli.py. With a src/ layout, pip install -e . once and -m works from anywhere.
  • Python decides from the module's package, __spec__.parent (and the older __package__). Run as a file both are None, and run with -m the package is 'myapp'. Adding __init__.py does not change that.
  • Big projects differ. Airflow bans relative imports with a lint rule (0 in 6,813 files across core, task SDK and providers). Django mixes them, with 2,991 absolute and 256 relative import lines in its package.

The repros below are real runs on Python 3.13.5 and pytest 9.2.0. The import counts come from ripgrep over clones of Django, FastAPI and Airflow, three Python repos from the set I index with repowise (a code analysis tool I build) for this series, November 2026.

Here is the error in its most common form. A small package, a CLI module that imports a sibling with a relative import, and a run that looks perfectly reasonable:

proj/ myapp/ __init__.py config.py # settings = {"greeting": "hello"} cli.py # from .config import settings 
$ python myapp/cli.py Traceback (most recent call last): File ".../proj/myapp/cli.py", line 1, in <module> from .config import settings ImportError: attempted relative import with no known parent package 

__init__.py is there. config.py is right next to cli.py. The import is correct. The problem is the command.

Why does Python say "no known parent package"?

A relative import is relative to a package, not to a folder. When Python sees from .config import settings, it takes the current module's package name, adds .config, and imports that. If the module has no package name, there is nothing to add .config to.

To see what Python thinks, I added a few lines to the top of cli.py, before the import:

import sys print("__name__ =", repr(__name__)) print("__spec__ =", __spec__ and f"parent={__spec__.parent!r}") print("__package__ =", repr(__package__)) print("sys.path[0] =", sys.path[0] or "''") from .config import settings 

Run as a file:

$ python myapp/cli.py __name__ = '__main__' __spec__ = None __package__ = None sys.path[0] = .../proj/myapp Traceback (most recent call last): File ".../proj/myapp/cli.py", line 8, in <module> from .config import settings ImportError: attempted relative import with no known parent package 

Run as a module, from proj/:

$ python -m myapp.cli __name__ = '__main__' __spec__ = parent='myapp' __package__ = 'myapp' sys.path[0] = .../proj hello 

Same file, same line 8. Two things changed:

  1. The package. python file.py loads the file as a standalone script called __main__ with no module spec and no package, so __spec__ and __package__ are both None. python -m myapp.cli imports myapp first, then runs cli as part of it, so the package is 'myapp' and .config resolves to myapp.config. The Python docs say the import system uses __spec__.parent and treats __package__ as a deprecated fallback, due to stop being used in 3.15. In both runs here the two agree. __name__ is '__main__' either way, so your if __name__ == "__main__": block still works under -m.
  2. sys.path[0]. A script run puts the script's own folder on sys.path. -m puts the current directory there. That second difference is what breaks people after they "fix" the import by making it absolute, more on that below.

The __init__.py file does not save you here. It makes myapp a regular package when something imports it as a package. Running one of its files by path never imports the package at all.

How do I fix it with python -m?

Run from the directory that contains the package, and name the module with dots, without .py:

cd proj python -m myapp.cli 

Two mistakes with -m produce their own errors. Both are worth knowing because the messages are confusing:

$ python -m myapp/cli.py python: Error while finding module specification for 'myapp/cli.py' (ModuleNotFoundError: No module named 'myapp/cli'). Try using 'myapp/cli' instead of 'myapp/cli.py' as the module name. $ python -m myapp.cli.py __name__ = 'myapp.cli' __spec__ = parent='myapp' __package__ = 'myapp' sys.path[0] = .../proj python: Error while finding module specification for 'myapp.cli.py' (ModuleNotFoundError: __path__ attribute not found on 'myapp.cli' while trying to find 'myapp.cli.py'). Try using 'myapp.cli' instead of 'myapp.cli.py' as the module name. 

The first suggestion (myapp/cli) is still wrong, since -m takes dots. The second one is sneaky: Python imported myapp.cli (the print lines ran, with __name__ set to 'myapp.cli'), then failed looking for a submodule called py.

Running from the wrong directory fails too, even with -m:

$ cd myapp && python -m cli __name__ = '__main__' __spec__ = parent='' __package__ = '' sys.path[0] = .../proj/myapp Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File ".../proj/myapp/cli.py", line 8, in <module> from .config import settings ImportError: attempted relative import with no known parent package 

From inside myapp/, cli is a top-level module, so its package is the empty string. Same error, different reason. The rule: the current directory (or something on sys.path) must hold the top-level package, and the module name you pass to -m must start with that package.

If you want python -m myapp with no submodule, add a myapp/__main__.py. All three repos I looked at ship one: Django's says python -m django check in its docstring, FastAPI's calls fastapi.cli.main(), and Airflow's holds the main() that its airflow console script points to.

What does "attempted relative import beyond top-level package" mean?

This is the sibling error. Add a subpackage that reaches up two levels:

# myapp/sub/tool.py from ..config import settings 

From proj/ it works. From inside myapp/ it does not:

$ python -m myapp.sub.tool tool sees {'greeting': 'hello'} $ cd myapp && python -m sub.tool Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File ".../proj/myapp/sub/tool.py", line 1, in <module> from ..config import settings ImportError: attempted relative import beyond top-level package 

In the second run the package is sub, one level deep. .. asks for the parent of sub, which does not exist as far as Python knows, because myapp was never imported as a package. Every dot needs a real package level above it, counted from where the import system thinks the top is. The fix is the same: run from proj/ with the full dotted name.

Why do I get "No module named ..." after switching to absolute imports?

The usual next move is to delete the dot. There are two ways to write it, and each one breaks under one of the two run styles.

from myapp.config import settings (absolute, with the package name):

$ python myapp/cli.py Traceback (most recent call last): File ".../abs/myapp/cli.py", line 1, in <module> from myapp.config import settings ModuleNotFoundError: No module named 'myapp' $ python -m myapp.cli hello 

from config import settings (no package name at all):

$ python myapp/cli2.py hello $ python -m myapp.cli2 Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File ".../abs/myapp/cli2.py", line 1, in <module> from config import settings ModuleNotFoundError: No module named 'config' 

This is the sys.path[0] difference from earlier. Run as a file, Python looks for imports next to the file, so myapp is not findable but config is. Run with -m from the project root, it looks in the project root, so myapp is findable and a bare config is not.

So from config import settings only works because of how you happened to launch it. It breaks when something imports myapp.cli as part of the package, your tests for example. from myapp.config import settings is the stable form, and it needs the same thing relative imports need: launch with -m from the root, or install the package.

Relative or absolute imports: what do big Python projects do?

Neither style is wrong, and these three projects chose differently. I counted import statements in the production packages of three repos with ripgrep (a line starting with from . counts as relative, a line starting with from <pkg> or import <pkg> counts as absolute):

Repo (commit) Layout Python files Relative imports Absolute imports of own package
Django d3954c9 flat (django/) 909 256 in 114 files 2,991 in 620 files
FastAPI a1b3be0 flat (fastapi/) 52 82 in 10 files 174 in 27 files
Airflow core 6a8bc71 src (airflow-core/src/airflow/) 788 0 3,966 in 620 files
Airflow task SDK src (task-sdk/src/airflow/) 183 0 1,142 in 159 files
Airflow providers (incl. tests) src (one src/ per provider) 5,842 0 14,208 in 3,593 files

What the counts show:

  • FastAPI keeps relative imports mostly in __init__.py files. 67 of its 82 are there, such as from .applications import FastAPI as FastAPI in fastapi/__init__.py.
  • Django uses them mostly between siblings. 63 of its 256 are in __init__.py files. The rest are modules importing a sibling in the same folder, such as from .client import DatabaseClient in the PostgreSQL backend's base.py (92 are in contrib/, 36 in the database backends). Only one line in all of Django's package goes up two levels: from ..utils import get_blank_choice_label in db/models/fields/reverse_related.py.
  • Airflow bans them. Its root pyproject.toml sets ruff's ban-relative-imports = "all" (rule TID252), and the count is 0 across 6,813 files. Airflow ships many distributions that share the airflow namespace (its __init__.py files call pkgutil.extend_path), so a full dotted path is unambiguous wherever the code ends up.
  • Airflow's one exception shows when relative imports are the better fit. Code under shared/ is symlinked into more than one place, for example as airflow._shared.timezones and as airflow.sdk._shared.timezones. An absolute import would point at only one of those, so the shared README says these libraries must use relative imports, and the lint config exempts shared/*/src/** from TID252. There are 45 relative imports across 22 of its 49 source files.

For how these packages fit together beyond their imports, the repowise blog has an architecture comparison of seven Python web frameworks, Django and FastAPI among them.

What I would do in a new project: absolute imports by default, and relative ones where the team agrees they read better, such as an __init__.py re-exporting its own submodules. Whichever you pick, the error in this post comes from how the code is launched, not from the import style.

How do src layout and an editable install fix it?

Airflow keeps its code under src/, which is now a common layout:

srcproj/ pyproject.toml src/ myapp/ __init__.py __main__.py config.py cli.py tests/ test_cli.py # from myapp.config import settings 

With the package under src/, the project root no longer contains it, so -m from the root fails:

$ python -m myapp.cli python: Error while finding module specification for 'myapp.cli' (ModuleNotFoundError: No module named 'myapp') 

That is the point of the layout. Nothing imports myapp by accident from the working directory, so your tests run against the installed package and not a loose folder. Install it once in editable mode:

# pyproject.toml [build-system] requires = ["setuptools>=69"] build-backend = "setuptools.build_meta" [project] name = "myapp" version = "0.1.0" 
$ pip install -q -e . $ python -m myapp.cli hello $ python -m myapp hello $ cd tests && python -m myapp.cli hello 

Setuptools finds src/myapp on its own. After the editable install, myapp is importable from any directory in that virtualenv, and edits to the source take effect without reinstalling. That last run from inside tests/ fails without the install, because tests/ does not contain myapp.

Airflow's architecture page shows what this looks like at scale: core, the task SDK and the providers each live under their own src/, and all of them install into the same airflow package.

Why does pytest raise it, and how do I fix that?

pytest has its own version of both errors. In the src project, before installing:

$ pytest -q tests/test_cli.py _____________________ ERROR collecting tests/test_cli.py ______________________ ImportError while importing test module '.../srcproj/tests/test_cli.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: .../importlib/__init__.py:88: in import_module return _bootstrap._gcd_import(name[level:], package, level) tests/test_cli.py:1: in <module> from myapp.config import settings E ModuleNotFoundError: No module named 'myapp' 

And a test that imports a helper next to it with a dot, in a tests/ folder with no __init__.py:

$ pytest -q tests/test_helpers.py ___________________ ERROR collecting tests/test_helpers.py ____________________ ... tests/test_helpers.py:1: in <module> from .helpers import make_settings E ImportError: attempted relative import with no known parent package 

pytest's default import mode (prepend) imports a test file under a name it works out from __init__.py files. With no __init__.py in tests/, test_helpers.py becomes a top-level module called test_helpers, so .helpers has no package. It is the script problem again.

Three fixes, all from these runs:

  • Install the package (pip install -e .). test_cli.py then passes. This does not help test_helpers.py, which still has no package of its own.
  • Or point pytest at src/ with its pythonpath setting. pytest -o pythonpath=src passed without installing. In config that is pythonpath = ["src"] under [tool.pytest.ini_options].
  • Add tests/__init__.py if your tests use relative imports. With it, both files passed (2 passed), because the test module is now tests.test_helpers.

FastAPI does the last one. 115 of its 652 test files use relative imports, and 80 of those lines are from ...utils import ..., three levels up from a file like tests/test_tutorial/test_additional_status_codes/test_tutorial001.py to tests/utils.py. That works only because tests/, tests/test_tutorial/ and each folder below it have an __init__.py. Django's test suite does something similar with its own runner: runtests.py lives in tests/, so running it puts tests/ first on sys.path, test apps such as tests/basic/ are packages, and 711 of 2,012 test files use relative imports such as from .models import ....

One more trap, in a flat layout with no tests/__init__.py:

$ pytest -q E ModuleNotFoundError: No module named 'myapp' $ python -m pytest -q 1 passed in 0.01s 

Same tests, same folder. python -m pytest adds the current directory to sys.path (the -m rule from earlier). The bare pytest command does not. If a test passes for you and fails in CI, check which of the two each side runs.

Why does it work in my IDE but not in the terminal (or the other way round)?

IDE run buttons are just one of the commands above with some settings attached.

  • VS Code. "Run Python File" runs python path/to/file.py, the script form, so a file with a relative import fails. For debugging, use a launch config with "module": "myapp.cli" in place of "program", and set "cwd" to the folder that holds the package.
  • PyCharm. A run configuration has a dropdown to run a "Script path" or a "Module name". Switch it to module name. PyCharm also adds content roots and source roots to PYTHONPATH by default, so code can import fine inside PyCharm and fail in a plain terminal. Marking src/ as a sources root hides the problem in the IDE, and the editable install fixes it everywhere.

You will also see sys.path.insert(0, ...) at the top of a file suggested as a fix. It works, it ties the code to one folder layout, and it hides the real issue, which is how the file was launched.

Checklist

  1. Give each package folder an __init__.py. Namespace packages can work without one, but pytest's default mode uses these files to work out package names. On its own it does not fix the error.
  2. Run modules as python -m package.module from the directory that contains package.
  3. With a src/ layout, run pip install -e . once per virtualenv.
  4. Pick an import style. If you want to enforce it, ruff's TID252 does what Airflow does.
  5. In pytest, install the package or set pythonpath = ["src"], and add tests/__init__.py if tests import each other with dots.
  6. Point IDE run configs at the module name, not the file.

Import errors and import cycles tend to arrive together, since the usual fix for a cycle is to move or defer an import. I covered that side in Circular imports in Python.

How I got these numbers

Every traceback above is from a real run on 29 November 2026 with Python 3.13.5 on Windows. The pytest and editable-install runs used a fresh virtualenv with pytest 9.2.0 (setuptools came in through pip's build isolation). I shortened the absolute paths in tracebacks to .../, wrote them with forward slashes, shortened the interpreter path to python, and cut pytest's banner, caret and summary lines. The import counts are ripgrep 15.1.0 runs over clones of Django at d3954c9, FastAPI at a1b3be0 and Airflow at 6a8bc71, counting lines that start with from . (relative) or from <pkg> / import <pkg> (absolute), so a multi-line import counts once. The table covers the package directories (django/, fastapi/, Airflow's airflow-core/src and task-sdk/src), plus all of Airflow's providers/ folder, tests included. Symlinks are not followed. I read the three repos' layouts and configs and did not run their code. The three repos come from the set I index with repowise for this series.

FAQ

How do I fix "ImportError: attempted relative import with no known parent package"?
Run the file as a module from the directory that contains your package: python -m myapp.cli, not python myapp/cli.py. If your code is under src/, run pip install -e . first. In pytest, add tests/__init__.py when tests use relative imports.

Does adding __init__.py fix the relative import error?
Not by itself. The repro above has __init__.py and still fails when run as python myapp/cli.py, because running a file by path gives it no package (__spec__ and __package__ are None). __init__.py matters once you run with -m or under pytest.

Should I use relative or absolute imports in Python?
Both work when the code is run as a module. Absolute imports name the full path, so a file can move to another folder without its own imports changing. Django has about 12 absolute import lines for every relative one, FastAPI uses most of its 82 relative imports in __init__.py re-exports, and Airflow bans relative imports except in code it symlinks into more than one package.