How to Use Relative Imports in Python?

Better Stack Team
Updated on June 19, 2024

Relative imports in Python are used to import modules relative to the current module's location in the package hierarchy. They are specified using dot notation to indicate the relative position of the module to be imported. Here's how you can use relative imports:

Suppose you have the following package structure:

 
my_package/
    __init__.py
    module1.py
    module2.py
    subpackage/
        __init__.py
        submodule1.py

Now, if you're in module1.py and you want to import module2.py, you can use a relative import:

 
# module1.py

# Relative import of module2.py
from . import module2

Similarly, if you're in submodule1.py and you want to import module1.py, you can use a relative import:

 
# submodule1.py

# Relative import of module1.py
from .. import module1

In relative imports:

  • A single dot . refers to the current package.
  • Two dots .. refer to the parent package.
  • You can use multiple dots to traverse up the package hierarchy as needed.

It's important to note that relative imports only work within packages. If you're trying to run a module directly as a script, relative imports will not work. In that case, you should use absolute imports or execute the module as part of a package.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.