Sub topic 9
Absolute versus relative imports
This chapter assumes you know the basic import forms, how sys.path is searched, and how a package with __init__.py is laid out. Inside a package, you can name another module in two ways: by its full path from a top-level package, or by its position relative to the current module.
Absolute imports
An absolute import names the module starting from a top-level name that Python can find on sys.path.
# shapes/circle.py
from shapes.util.mathx import square
def area(r):
return 3.14159 * square(r)The import reads the same wherever the file sits. If you move circle.py to another subpackage, the line still works. PEP 8 recommends absolute imports as the default.
Relative imports
A relative import starts with one or more dots. The dots are counted from the package that contains the current module.
# shapes/circle.py
from .util.mathx import square
def area(r):
return 3.14159 * square(r)| Syntax | Meaning from inside `shapes/util/mathx.py` |
|---|---|
| `from . import x` | `x` from `shapes.util`, the current package |
| `from .y import x` | `x` from `shapes.util.y`, a sibling module |
| `from .. import x` | `x` from `shapes`, the parent package |
| `from ..circle import area` | `area` from `shapes.circle` |
Relative imports always use the from ... import ... form. A statement like import .util is a syntax error.
How Python resolves the dots
Python does not look at directories to resolve a relative import. It reads the module's __package__ attribute, which holds the dotted package name, and applies the dots to that name. This explains the most common error.
python shapes/circle.py
# ImportError: attempted relative import with no known parent packageWhen you run a file directly, Python sets its name to __main__ and gives it no package. The dots then have nothing to count from. Run it as part of the package instead, from the directory that contains shapes/:
python -m shapes.circleNow __package__ is shapes, and .util.mathx resolves to shapes.util.mathx. Chapter material on python -m covers this in more detail.
Choosing between them
- Use absolute imports for most code. They are explicit and easy to search for.
- Use relative imports within a package that you may rename or vendor, or when the full path is long.
- Use absolute imports in scripts and entry points, because relative imports need a parent package.
- Do not mix styles for the same target within one file.
Exercise
Exercise
Inside shapes/util/mathx.py, which line imports the module shapes.circle using a relative import, and why does running python shapes/util/mathx.py fail on it?
Show answer
Use from .. import circle. Two dots refer to the parent package shapes. Running the file directly makes its name __main__ with no package, so Python has nothing to apply the dots to and raises "attempted relative import with no known parent package". Run python -m shapes.util.mathx from the directory containing shapes/ instead.