Explaining Relative Imports in Python

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.

import demo_reader.compressed.bzipped
from demo_reader.compressed import bzipped
# 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
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)

--

--

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com