Modules and Packages – Using import in Python

The Python import statement is used to pull module and package definitions into a program (or into another module).  This section gives the basic, most commonly used syntax for the import statement; see the standard Python documentation for more possibilities.

Modules

Form 1: import modname

Imports the module contained in the file “modname.py”.  Global symbols (variables, functions, and classes defined at the top level) can be access using dot notation, with “modname” as left argument (e.g., modname.f()).

Form 2: import modname as alias

As in form 1, this statement imports the file name modname.py, but the global symbols are now accessed using “alias” instead of “modname” (e.g., alias.f()).

Form 3: from modname import g

This form of the import statement imports only the specified names into the program. Accessing the symbol does not require a qualifier (e.g., g alone is sufficient).

Form 4: from modname import g as h

This form combines forms 2 and 3, allowing a specific symbol to be imported, then renamed for local use in the importing module.

Form 5: from modname import *

Import all symbols from modname into the current namespace.  This form can lead to confusion (e.g., by importing a large number of symbols) and we do not recommend it.

Packages

In all of the forms above, the “modname” can be a package name or dot-separated list of package names, possibly ending in module name.  The effect is to traverse the directory path of the first (left most) package, through a list of sub-packages, to a final module.  The symbols in that module or package are then imported into the current namespace.

Form 1: import pname.modname

Imports the module modname (i.e., in file modname.py) from the package pname (i.e., in directory pname).  The directory pname must appear on sys.path.  Symbols defined in modname are referenced using the full-qualifed path, e.g., pname.modname.f().

Form 2: import pname.modname as alias

Because package, subpackages, and module names can get long, the alias mechanism is handle to simplify access to function names.  This syntax allows a simple alias to reference an entire dot-separated sequence like package.subpackage.subsubpackage.modname, etc.  (A common example is to import matplotlib.pyplot as plot.)

Form 3: from pname.modname import cname

A common idiom is to use a specific class from a module in a package.  This form of the import accomplishes that task.  (An example is “from matplotlib.pyplot import Button”.)