Relative imports in Python 3 use explicit leading dots (from . import sibling for the current package directory, from .. import parent for one level up) to resolve modules relative to the importing module’s __package__ attribute—and work only when the file is imported as part of a package or executed as a module via python -m package.module, never when run directly as a top-level script (python package/module.py).
Basic Example
Consider the following package directory layout:
my_app/
├── __init__.py
├── config.py
└── services/
├── __init__.py
├── auth.py
└── user_service.py
Inside my_app/services/user_service.py:
# 1. Single dot (.) -> import from the SAME package directory (my_app/services/)
from . import auth
from .auth import verify_token
# 2. Double dot (..) -> import from the PARENT package directory (my_app/)
from .. import config
from ..config import DATABASE_URL
def get_active_user(token: str) -> dict:
user_id = verify_token(token)
return {"user_id": user_id, "db": DATABASE_URL}
Run from the parent directory containing my_app/ using -m:
python -m my_app.services.user_service
Key Details & Common Pitfalls
- Why
python my_app/services/user_service.pyfails (ImportError: attempted relative import with no known parent package): When you execute a file directly by file path, Python sets its__name__to"__main__"and its__package__toNone(or""). Without a parent package name in__package__, Python cannot anchor leading dots (.or..).- Fix: Always run package entry points from outside the package root using
python -m my_app.services.user_service, or expose a top-level runner script (main.py) outsidemy_app/that uses absolute imports (from my_app.services import user_service).
- Fix: Always run package entry points from outside the package root using
- Dot depth rules (
ValueError: attempted relative import beyond top-level package):.= current package directory (my_app/services)..= parent package directory (my_app)= grandparent package directory- You cannot traverse above the top-level package (
my_app). Tryingfrom ... import somethinginsidemy_app/services/user_service.pyraisesValueError: attempted relative import beyond top-level package.
from . import modulesyntax is mandatory (neverimport .module): Python syntax forbidsorimport ..config(SyntaxError). Relative imports must always use thefrom <dots>[module] import <name>form.- Role of
__init__.py: Although Python 3.3+ supports implicit namespace packages without__init__.py, including__init__.pyin every package folder ensures explicit package boundaries, cleaner IDE/test runner discovery (pytest), and allows re-exporting sub-module symbols cleanly at the package level (e.g.,from .auth import verify_tokeninsideservices/__init__.py). - PEP 8 recommendation (Absolute vs. Relative): PEP 8 recommends absolute imports (
from my_app.config import DATABASE_URL) as the default because they remain readable if a file moves, while explicit relative imports (from .auth import verify_token) are ideal inside deeply nested packages where typing the full package path becomes verbose or when renaming the top-level package shouldn’t require editing internal imports.
Comparison of Relative vs. Absolute Imports in Python 3
| Import Style | Example Syntax | Works When Run Directly (python file.py)? |
Works With python -m pkg.mod? |
Best Used When |
|---|---|---|---|---|
Same-directory relative (.) |
from . import auth / from .auth import fn |
No (ImportError) |
Yes | Importing tightly coupled sibling modules inside the same subpackage. |
Parent-directory relative (..) |
from .. import config / from ..config import X |
No (ImportError) |
Yes | Accessing shared utilities or config one level up inside a package. |
| Absolute import (PEP 8 default) | from my_app.config import DATABASE_URL |
Only if project root is on sys.path |
Yes | Cross-package imports, tests, and entry-point scripts for maximum clarity. |
| Implicit relative (Python 2 legacy) | import auth (inside services/) |
N/A | No (removed in Python 3) | Never—Python 3 treats bare import auth strictly as a top-level absolute import. |
You must log in or register to comment.
