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 |
from | fetch particular names from a module |
imp.reload (reload in 2.X) | reload a module's code without stopping Python |
In practice, programs usually involve more than just one file.
Python uses a modular program structure that groups functionality into coherent and reusable units.
Suppose we have three files: a.py, b.py, and c.py.
The file a.py is chosen to be the top-level file.
The files b.py and c.py 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 b.py
def test(text): # File b.py print(text, 'test')
Now, suppose a.py wants to use test. The content of a.py:
import b # File a.py b.test('gumby') # Prints "gumby test"
The code import b roughly means:
Load the file b.py unless it's already loaded, and give me access to all its attributes through the name b.
A program includes the following files:
Main scripts and modules are both text files containing Python statements.