Sub topic 9
Absolute versus relative imports
This chapter assumes you can write functions and classes, run scripts from a terminal, and know that a package is a directory of modules with an __init__.py file. It also assumes you know that sys.path lists the places Python searches for top-level modules. Here you will learn how a module inside a package refers to its neighbors, and which errors appear when you get it wrong.
Two ways to name a module
Inside a package, one module often needs another. Python gives you two ways to write that.
- An absolute import gives the full dotted name, starting from a top-level package on
sys.path. - A relative import gives a position, counted from the package that contains the current module.
We will use this layout throughout:
shapes/
__init__.py
circle.py
util/
__init__.py
mathx.pyHere is mathx.py and a version of circle.py that imports from it:
# shapes/util/mathx.py
def square(x):
return x * x
# shapes/circle.py
from .util.mathx import square
def area(r):
return 3.14159 * square(r)The leading dot in .util.mathx means "the package that contains this module". Because circle.py lives in shapes, the dot stands for shapes, so the import resolves to shapes.util.mathx.
Absolute imports
An absolute import names the module from the top. The same line in circle.py written absolutely is:
from shapes.util.mathx import squareAbsolute imports have three advantages:
- They read the same in every file, so you can copy a line between modules.
- They show where a name comes from without counting dots.
- They keep working if you move the importing module to another package, as long as the target stays put.
Their cost is that the top-level package name is hard-coded. If you rename shapes to geometry, every absolute import in the package must change. PEP 8 recommends absolute imports as the default for this reason: they are clearer, and they give better error messages when something is wrong.
Relative imports
A relative import uses leading dots, and each extra dot goes one level up.
| Form | Meaning inside `shapes/util/mathx.py` | Resolves to |
|---|---|---|
| `from . import x` | the current package | `shapes.util` |
| `from .other import y` | a sibling module | `shapes.util.other` |
| `from .. import z` | the parent package | `shapes` |
| `from ..circle import area` | a module in the parent | `shapes.circle` |
| `from ..util.mathx import square` | back down through the parent | `shapes.util.mathx` |
Relative imports have these properties:
- They survive renaming the top-level package, since the package name is never written.
- They make a subpackage easy to move or vendor as a unit.
- They work only with the
from ... import ...form. Writingimport .utilis a syntax error. - They are valid only inside a package. You cannot use them to reach a module outside the package that contains the file.
How Python resolves a relative import
A relative import is converted to an absolute name before the search happens. Python reads the importing module's __package__ attribute (falling back to __name__ and __path__ in some cases). It then strips one trailing component for each extra dot and joins the rest with the name you wrote.
You can see the inputs:
# shapes/util/mathx.py
print(__name__) # shapes.util.mathx
print(__package__) # shapes.utilWith __package__ equal to shapes.util, the line from ..circle import area strips one component to get shapes, then appends circle. The result is shapes.circle, which then goes through the normal sys.modules check and finder search described in earlier chapters.
This explains the most common relative-import failure. The name that matters is the module's __name__ as Python knows it, not its path on disk.
The error: attempted relative import with no known parent package
Suppose you run a file inside the package directly:
python shapes/circle.pyPython executes the file as the top-level script. Its __name__ is "__main__" and its __package__ is empty, so Python has no package to count dots from. The import fails with:
ImportError: attempted relative import with no known parent package(Depending on the Python version and how the file was started, you may see attempted relative import beyond top-level package instead. That message means you used more dots than the package has levels.)
There are two fixes:
- Run the module as part of the package with
-m, from the directory that containsshapes/:
``text python -m shapes.circle ``
Now __name__ is "__main__" but __package__ is "shapes", so the dots resolve correctly.
- Use absolute imports and make sure the project root is on
sys.path, for example by installing the package in editable mode.
A third approach, editing sys.path at the top of the file, tends to cause trouble. It can import the same file under two names, which creates two separate module objects.
A second trap: the same file imported twice
If sys.path contains both the project root and shapes/ itself, the module circle can be reachable as circle and as shapes.circle. Python keys sys.modules by name, so these become two distinct module objects with separate globals. A class defined in the file then exists twice, and isinstance checks between the two copies fail in confusing ways.
You can check for this:
import sys
for name, mod in sorted(sys.modules.items()):
if name.endswith("circle"):
print(name, getattr(mod, "__file__", None))If you see two entries with the same __file__, you have a duplicate. The cure is to put only the project root on sys.path and import everything through the package name.
Choosing between them
| Situation | Prefer |
|---|---|
| Code outside the package (scripts, tests, other packages) | Absolute |
| Imports between sibling modules in a package you may rename or move | Relative |
| Reaching a distant module, such as `from ....a.b import c` | Absolute |
| Library code that users read to learn the layout | Absolute |
| A subpackage meant to be vendored under a different name | Relative |
A practical rule: use absolute imports by default. Use a relative import when the target is a close neighbor, meaning one or two dots. More than two dots usually signals that an absolute import would be easier to read.
Do not mix the two styles for the same target within one package. Consistency matters more than which style you pick, because mixed styles make it harder to search for every place a module is imported.
Interaction with `__init__.py`
An __init__.py file is also a module, and relative imports work there too. The package's public interface is often built with them:
# shapes/__init__.py
from .circle import area as circle_area
__all__ = ["circle_area"]In __init__.py, the single dot refers to the package itself, because the file is the package's own module. In shapes/__init__.py, .circle means shapes.circle. In shapes/util/__init__.py, .mathx means shapes.util.mathx.
This is a place where relative imports are especially natural, since the package is describing its own contents.
Implicit relative imports are gone
In Python 2, import circle inside shapes/util/ could silently find a sibling module before searching sys.path. Python 3 removed this. An import without dots is always absolute, so import circle in that file looks only at top-level names. If you have old code that depends on the implicit behavior, convert each such line to either from . import circle or from shapes import circle.
Common errors summary
| Symptom | Cause | Fix |
|---|---|---|
| `no known parent package` | File run directly as a script | Use `python -m package.module` |
| `beyond top-level package` | Too many dots for the package depth | Remove dots or use absolute |
| `ModuleNotFoundError: No module named 'shapes'` | Project root is not on `sys.path` | Run from the root or install the package |
| `SyntaxError` on `import .x` | Relative form needs `from` | Write `from . import x` |
| Two copies of one module | File reachable under two names | Keep only the project root on `sys.path` |
Exercise
A file app/services/billing.py contains from ..models import Invoice, and app has __init__.py files in both app and app/services. You run python app/services/billing.py and get "attempted relative import with no known parent package". What command fixes it, from which directory, and what absolute import is equivalent to the line?
Show answer
Run python -m app.services.billing from the directory that contains app/. The equivalent absolute import is from app.models import Invoice. With -m, __package__ is app.services, so two dots resolve to app.
Exercise
In shapes/util/mathx.py, which module does from .. import circle import, and why does import .circle fail?
Show answer
It imports shapes.circle, because two dots from shapes.util go up to shapes. The statement import .circle fails because relative imports are allowed only in the from ... import ... form, so it is a syntax error.