Home › Python

ImportError: attempted relative import beyond top-level package (Python) — how to fix

Traceback (most recent call last):
  File "/home/me/project/app/api/routes.py", line 1, in <module>
    from ..models import User
ImportError: attempted relative import beyond top-level package

Quick fix: Run from the project root as a module: cd project && python -m app.api.routes (not python app/api/routes.py or cd app && python -m api.routes). Or switch to absolute imports like from app.models import User.

What it means

Each leading dot in a relative import goes up one package level: . is the current package, .. is its parent. Python works out the levels from the module's full name (__name__), and that name depends on how you started the program, not on the folder layout.

Layout:

project/
  app/
    __init__.py
    models.py
    api/
      __init__.py
      routes.py      # from ..models import User

Fix 1: run from the project root with -m

cd project
python -m app.api.routes

Use dots, not slashes, and no .py. The current directory (project) is added to sys.path, so app becomes the top-level package.

For a web app, start it the same way from the root, for example uvicorn app.main:app or python -m flask --app app run.

Fix 2: use absolute imports

Absolute imports don't depend on how deep the current module is:

# app/api/routes.py
from app.models import User

These work as long as project/ is on sys.path (running from the root, pip install -e ., or PYTHONPATH=project).

Fix 3: add the missing init.py

Every directory in the chain should be a package. If app/ lacks __init__.py, some tools (notably pytest) decide the top-level package is api and .. breaks. Add empty __init__.py files to each package directory.

Fix 4: pytest

pytest computes the module name from the nearest directory without __init__.py. Either:

[tool.pytest.ini_options]
pythonpath = ["."]

and use absolute imports (from app.models import User) in the tests.

Fix 5: install the project

For anything bigger than a script, make it installable and install it in editable mode:

python -m pip install -e .

(with a minimal pyproject.toml). Then app is importable from anywhere and absolute imports always work.

Don't: sys.path hacks

sys.path.append("..") at the top of a file may make it run, but it depends on the current working directory and breaks as soon as you start the program from somewhere else.

If your error says "with no known parent package" instead, you ran the file directly as a script; see that page.

Last updated 2026-12-01.