Python - Module Module Introduction


Modules correspond to Python program files.

Each file is a module.

Modules can import other modules to use the function and logics they define.

Modules are processed with two statements and one important function:

Command Description
import fetch a module as a whole
fromfetch particular names from a module
imp.reload (reload in 2.X) reload a module's code without stopping Python

Python Program Architecture

In practice, programs usually involve more than just one file.

Python uses a modular program structure that groups functionality into coherent and reusable units.

Imports and Attributes

Suppose we have three files:,, and

The file is chosen to be the top-level file.

The files and are modules. They are not usually launched directly.

Modules are normally imported by other files and they will be used as library.

Here is the content of

def test(text):                # File 
     print(text, 'test') 

Now, suppose wants to use test. The content of

import b                       # File 
b.test('gumby')                # Prints "gumby test" 

The code import b roughly means:

Load the file unless it's already loaded, and give me access to all its attributes through the name b. 

A program includes the following files:

  • one top-level script file which is launched to run the program
  • multiple module files imported as libraries.

Main scripts and modules are both text files containing Python statements.