Python Absolute And Relative Imports

15 Apr 2014

When to use absolute imports and relative imports? Which one is the standard practice in Python programming?

The rationale is to use absolute import and EXPLICIT relative import.

Intra-packages reference needs to be unambiguous to avoid package/module name collisions, however, it has become more and more difficult to implement since the number of Python libraries keeps growing and more and more existing packages’s internal modules shadow standard libary. Therefore it has been decided (see PEP328) that from python 3 (or 2.7?), absolute import is the default behavior when you write import statements like this:

import foo

This import tells Python that foo will always be a module or package reachable from sys.path. This is called an absolute import.

Keep in mind: import <> is always absolute, relative import must always use from <> import. In addition, absolute imports can also use from <> import by omitting the leading dots.

That means, absolute imports could provide all the functionalities of relative (intra-package) imports, while relative imports have only intra-package use and had better be explicit.

Notice that although absolute imports provide ALL the functionalities of import statements, relative imports have advantages for intra-package usecase and have reasons to stay in Python.

For some historical backgrounds; the above import statement was ambiguous in Python 2.4 or earlier, which might refer to a top-level module or to another module inside the same package as the importing module. And, in Python 2.4 (and earlier), absolute imports were not introduced and relative imports were discouraged since the syntax wasn’t finalized yet. For Python 2.5 and 2.6, absolute imports introduced and can be ‘turned on’ through the use of:

from __future__ import absolute_import

In conclusion, relative imports makes your life easier when rearranging packages/modules (so that you don’t need to change dozens of internal imports) and it is NOT discouraged anymore since the syntax has been finalized and approved by BDFL. Use it for intra-package references and use it with explicit syntax (with leading dots); Pylint actually complains when not using relative imports for intra-package references.

Python pda project provides good examples for this standard pratice. To see some more examples of intra-package imports: