Python Import Standards

Detailed documentation(PEP328) on Python’s importing standards are provided here.

In this post, we will go over the following concepts:

  1. Multi-line import
  2. Absolute import
  3. Relative import

Multi-line import

The first rule is that multi-line imports can be wrapped with a paranthesis.

from Tkinter import (Tk, Frame, Button, Entry, Canvas, Text,

Absolute import

If you have a module named ‘’, when you do,

import string

you would not know whether the Python’s standard ‘’ library is being imported or your private module is being imported. The absolute imports are recommended to avoid this ambiguity.

In Python 3, the absolute import is set to the default. However, in Python 2, you need to manually enable the absolute import.

from __future__ import absolute_import

In the following package structure,


when you want to import a function in from, you would use,

from package.subpackage1.moduleX import a_function

Even though this import statement is residing within, Python import will search upward the directory structure until you find a package named ‘package’, and traverse down.

This absolute import syntax is more explicit and readable, and it has been suggested to use absolute imports over the traditional relative import

Relative import

When you use relative imports, the import statement does not require the actual name of package structure anymore. It instead focuses on the physical structure of the package.

In the following package structure, package/ subpackage1/ subpackage2/

Assuming that the current file is either or subpackage1/ , following are correct usages of the relative imports:

from .moduleY import spam
from .moduleY import spam as ham
from . import moduleY
from ..subpackage1 import moduleY
from ..subpackage2.moduleZ import eggs
from ..moduleA import foo
from ...package import bar

There are some cases where a relative import has benefits compared to an absolute import. The most important of which is being able to rearrange the structure of large packages without having to edit sub-packages. This is actually highly encouraged in building Django web application, since you can use your Django application in a modular manner.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s