Learn with diagrams, code, systems and practical examples.
Modules and Packages
Split code into files and import reusable functionality.
As programs grow, modules help organize related behavior instead of keeping everything in one file.
Start with the idea
A Python file can act as a module. import lets one module use names from another. Packages organize related modules into a directory structure.
Small working example
Run this example first. Do not change several things at once; confirm the basic behavior, then experiment.
# math_helpers.py
def double(value):
return value * 2
# app.py
from math_helpers import double
print(double(6)) A Python file can act as a module. import lets one module use names from another. Packages organize related modules into a directory structure.
- Modules are Python files.
- Packages group modules.
- Imports should reflect clean dependency direction.
12The example is intentionally small. Focus on the chapter’s main idea before adding extra syntax or framework code.
Common beginner mistake
Creating circular imports where modules depend on each other in a loop.
Keep responsibilities clear and move shared contracts into a lower-level module when needed.
Quick recap
- Modules are Python files.
- Packages group modules.
- Imports should reflect clean dependency direction.
Try it yourself
These are deliberately small. If you can complete them without copying the example, you are ready to continue.
- Move one function into a separate module.
- Import it from a small app file.