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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github