Search⌘ K

Relative Imports

Explore the concepts and syntax of relative imports in Python as described in PEP 328. Understand how to use periods to navigate modules within packages, avoid standard library shadowing, and properly structure your code into packages. Learn the differences in running relative imports in Python 2 and Python 3, including common errors and solutions for module execution within packages.

Why do we need relative imports?

PEP 328 describes how relative imports came about and what specific syntax was chosen. The idea behind it was to use periods to determine how to relatively import other packages / modules. The reason was to prevent the accidental shadowing of standard library modules. Let’s use the example folder structure that PEP 328 suggests and see if we can get it to work:

Javascript (babel-node)
my_package/
__init__.py
subpackage1/
__init__.py
module_x.py
module_y.py
subpackage2/
__init__.py
module_z.py
module_a.py

Create the files and folders above somewhere on your hard drive.

...