Name

The import Statement

Synopsis

import module [, module]*
import [package.]* module [, [package.]* module]*
import module as name

Module access: imports a module as a whole. Modules contain names fetched by qualification (e.g., module.attribute). module names the target module—a Python file or compiled module located in a directory in sys.path (PYTHONPATH), without its filename suffix (e.g., omit the “.py”). Assignments at the top level of a Python file create module object attributes. The as clause assigns a variable name to the imported module object; useful to provide shorter synonyms for long module names.

Import operations compile a file’s source to byte-code if needed (and save it in a .pyc file if possible), then execute the compiled code from top to bottom to generate module object attributes by assignment. Use the reload built-in function to force recompilation and execution of already-loaded modules; see also _ _import_ _ used by import, in Section 1.12.

In the Jython implementation, imports may also name Java class libraries; Jython generates a Python module wrapper that interfaces with the Java library. In Standard (C) Python, imports may also load compiled C and C++ extensions.

Package imports

If used, package prefix names give enclosing directory names, and module dotted paths reflect directory hierarchies. An import of the form import dir1.dir2.mod loads the file at directory path dir1/dir2/mod.py, where dir1 must be contained by a directory listed on PYTHONPATH. ...

Get Python Pocket Reference, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.