DEV Community

Cover image for python relative import

Posted on

python relative import

Like any other modern programming language, in Python you can import code from other files or modules. If you used Python before, you know that you can use modules.

With modules (packages) you can use already existing code bases in your own code, saving you a lot of development time.

You can import any module with the import keyword.

import math
import sys
import os

Before playing with modules, you should know the basics of Python.

So what is an absolute and a relative import?

Absolute import

Absolute import defines the resource to be imported by its full path (projects root). You likely already have used absolute imports, as its the default way of importing modules in Python.

These are examples of absolute imports:

import package

And this:

from package.firstmodule import firstmodule

Relative import

A relative import imports the resource relative to the current location.

In other words, with relative imports you specify where your resources are relative to the current python script.

# Import names from pkg.string
from .string import name1, name2

# Import pkg.string
from . import string

You can see the dot in front of the module, relative imports use dot notation.

A single dot means the current directory, you may be familiar with this from Linux or command prompt where:

  • dot (.) means current directory
  • dot dot (..) means parent directory
  • dot dot dot (...) means grandparent directory

Which to use

You should use absolute imports, unless you have a reason not to. Absolute imports are clear and easy. It specifies where the imported resource is, just by looking at it.

New modules can be installed with pip, which saves you from having to commit many packages inside your code base.

Related links

Top comments (0)