Modules and Packages
Split a growing program into files you can reuse, import and ship
.py file. A package is a directory of modules. Instead of one giant script, you organise related code into named files and pull exactly what you need into other files with import. This is how every real Python project — from a 200-line tool to a framework like Django — is structured.
- explain what a module is and write your own,
- use every import form (
import,from ... import,as) and know their trade-offs, - describe how Python locates a module (
sys.path) and what__pycache__is, - use the
if __name__ == "__main__":guard correctly, - build a package with
__init__.pyand choose absolute vs relative imports.
1. What exactly is a module?
In the beginner course you called import math and import random — modules that ship with Python. The secret is underwhelming in the best way: a module is just a file of Python code. Any file you save with a .py extension is already a module, and its filename (without .py) is the module name.
Suppose you write geometry.py:
# geometry.py
PI = 3.14159
def circle_area(radius):
return PI * radius * radius
def rectangle_area(width, height):
return width * height
From another file in the same folder you can now reuse that code:
# main.py
import geometry
print(geometry.circle_area(2))
print(geometry.PI)
Output:
12.56636
3.14159
The names defined at the top level of geometry.py — PI, circle_area, rectangle_area — become attributes of the module object, reached with dot notation: geometry.circle_area. Modules turn a folder of files into a toolbox you can pick from.