Explaining Relative Imports in Python

Pavol Kutaj
1 min readMar 18, 2023

--

The aim of this page📝is to introduce the concept of relative imports in Python. Although they…

  1. Can reduce typing in deeply nested package structures
  2. Promote a certain form of modifiability (to potentially rename top-level and subpackages)

…the consensus is to avoid relative import in most cases In any case, the syntax is good to recognize.

In absolute imports, you specify the complete ancestry of modules

import demo_reader.compressed.bzipped
from demo_reader.compressed import bzipped

In relative imports, you use dots to signify a parent or a grandparent of a given module

# importing a function from grandparent module
from . import name
from .. import name
from .module_name import name
from ..module_name import name
  • each dot before the module name stands for
  • first . parent of the current module
  • two .. stands for grandparent of the current module
  • you can only use relative imports with the from/import form of the import statement
  • NEVER import ..module_namesyntax error
from <module> import <name>
  • NOTE: relative imports can be used only within the current top-level package
  • NEVER for importing modules outside of that package

Let’s look at an exemplary folder structure with a relative import

demo_reader

├───demo_reader
│ │ multireader.py
│ │ __init__.py
│ │
│ ├───compressed
│ │ bzipped.py
│ │ gzipped.py
│ │ __init__.py
│ │
│ └───util
│ writer.py
│ __init__.py

└───tests
multireader_test.py
__init__.py
  • the absolute import would be from demo_reader.util import writer
import bz2
from ..util import writer

opener = bz2.open

if __name__ == "__main__":
writer.main(opener)

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com