Python - Module from...import...

import Statement

Consider the following code in

def printer(x):                   # Module attribute 

In the following code the name module1 serves two different purposes:

  • it identifies an external file to be loaded, and
  • it becomes a variable in the script, which references the module object after the file is loaded:
import module1                         # Get module as a whole (one or more) 
module1.printer('Hello world!')        # Qualify to get names 

from Statement

from statement allows us to use the copied names directly in the script without going through the module:

from module1 import printer            # Copy out a variable (one or more) 
printer('Hello world!')                # No need to qualify name 

from * Statement

You can use a special form of from.

When we use a * instead of specific names, we get copies of all names assigned at the top level of the referenced module.

from module1 import *                   # Copy out _all_ variables 
printer('Hello world!') 

Imports Happen Only Once

Modules are loaded and run on the first import or from, and only the first.

Related Topics