Chapter 6
Introduction to Modules
In Python, a module is a file containing Python definitions and statements. The file name is the module name with the suffix .py
added. For example, a file named my_module.py
would be a module containing Python definitions and statements.
A module can define functions, classes, and variables. A module can also include runnable code. For example, the following my_module.py
file defines a function named hello()
:
def hello():
print("Hello, World!")
You can use the import
statement to include the definitions from a module in your program. Once a module is imported, you can use its functions, classes, and variables like any other Python object. Here is an example that imports the my_module
module and calls the hello()
function:
import my_module
my_module.hello()
Introduction to Packages
A package is a collection of modules. Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B
designates a submodule named B
in a package named A
.