A module is any Python file (.py) that can be imported into another Python program. When you write import math, Python loads the math module, executes its code (if not already cached), and creates a module object whose attributes are the names defined in that file. Modules are Python's primary mechanism for code organisation and reuse.
Modules have their own namespace: names defined inside a module do not clash with names in other modules. The import statement provides several variations: import math (access via math.sqrt), from math import sqrt (direct access to sqrt), and from math import * (import everything, generally discouraged). The as keyword allows aliasing: import numpy as np.
Every Python file is a module, and every module has a __name__ attribute. When a file is run directly, __name__ is set to "__main__"; when imported, it is set to the module's dotted name. The if __name__ == "__main__": guard lets a file serve both as a reusable module and as a standalone script. Modules are cached in sys.modules after first import, so subsequent imports are fast and idempotent.
Discussed in:
- Chapter 12: Modules and Packages — What Is a Module