What is absolute import in python?

The distinction between absolute and relative that’s being drawn here is very similar to the way we talk about absolute and relative file paths or even URLs.

An absolute {import, path, URL} tells you exactly how to get the thing you are after, usually by specifying every part:

import os, sys
from datetime import datetime
from my_package.module import some_function

Relative {imports, paths, URLs} are exactly what they say they are: they’re relative to their current location. That is, if the directory structure changes or the file moves, these may break (because they no longer mean the same thing).

from .module_in_same_dir import some_function
from ..module_in_parent_dir import other_function

Hence, absolute imports are preferred for code that will be shared.


I was asked in comments to provide an example of how from __future__ import absolute_import ties into this, and how it is meant to be used. In trying to formulate this example, I realized I couldn’t quite explain its behavior either, so I asked a new question. This answer gives a code sample showing a correctly working implementation of from __future__ import absolute_import, where it actually resolves an ambiguity.

The accepted answer goes into more detail about why this works the way it does, including a discussion of the confusing wording of the Python 2.5 changelog. Essentially, the scope of this directive (and by extension the distinction between absolute and relative imports in Python) is very, very narrow. If you find yourself needing these distinctions to make your code work, you’re probably better off renaming your local module if at all possible.

Leave a Comment