Python - import and from statement

Introduction

import and from are executable statements, not compile-time declarations.

They may be nested in if tests, to select among options.

They are not resolved or run until Python reaches them while executing your program.

The imported modules and names are not available until their associated import or from statements run.

import statement assigns an entire module object to a single name.

from statement assigns one or more names to objects of the same names in another module.

The names copied with a from become references to shared objects.

Example

Consider the following file, small.py :

x = 1 
y = [1, 2] 

When importing with from, we copy names to the importer's scope that initially share objects referenced by the module's names:

from small import x, y         # Copy two names out 
x = 42                         # Changes local x only 
y[0] = 42                      # Changes shared mutable in place 

Here, x is not a shared mutable object, but y is.

The names y in the importer and the importee both reference the same list object, so changing it from one place changes it in the other:

import small # Get module name (from doesn't) 
small.x      # Small's x is not my x 
small.y      # [42, 2] 

Related Topic