Resolve Relative Imports inside Packages
Core idea
An explicit relative import begins with dots after from. One dot refers to the current package; two dots refer to its parent package. These imports rely on package context rather than the current working directory.
Import a sibling module
In a new empty directory, create the parent folders and these files (an empty file is marked by its filename alone):
bm_shop/__init__.py
bm_shop/codes.py
number = 4bm_shop/report.py
from .codes import numberdef label(): return f"Box-{number}"Save the following code as run.py and run python run.py from the new directory. Use a fresh directory for each example.
Output: Box-4. The relative import in report.py resolves .codes inside bm_shop.
Import from a parent package
In a new empty directory, create the parent folders and these files (an empty file is marked by its filename alone):
bm_shop/__init__.py
bm_shop/settings.py
currency = "EUR"bm_shop/reports/__init__.py
bm_shop/reports/summary.py
from ..settings import currencydef describe(): return currencySave the following code as run.py and run python run.py from the new directory. Use a fresh directory for each example.
from bm_shop.reports.summary import describeprint(describe())Output: EUR. Two dots move from bm_shop.reports to bm_shop; settings is then resolved there.
Run a relative-import module with -m
In a new empty directory, create the parent folders and these files (an empty file is marked by its filename alone):
bm_shop/__init__.py
bm_shop/codes.py
number = 9Save the following code as bm_shop/report.py and run python -m bm_shop.report from the new directory. Use a fresh directory for each example.
Output: 9. The -m form establishes package context for the relative import. Running the same file directly as a path normally raises ImportError instead.
Common mistake
import .codes is not valid syntax. Also avoid adding arbitrary directories to the import search path just to fix a missing package context; use the proper entry point.
Practice
In the third example, compare python -m bm_shop.report with python bm_shop/report.py from the parent directory. Explain why only the first has package context.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Resolve package-relative paths
Check your understanding of relative imports.
Inside bm_shop.report, which import selects number from bm_shop.codes using a relative path?
Inside bm_shop.reports.summary, what does `from ..settings import currency` target?
Why can `python bm_shop/report.py` fail on a sibling relative import?
Which invocation preserves package context from the parent directory?