What Are Modules?
Understand why splitting code into multiple files matters
One file works — until it doesn't
In earlier courses, all your code lived in a single file. That works fine for small scripts. But real projects grow. A 500-line file with functions for reading files, processing data, and printing results becomes hard to navigate, hard to test, and hard to share.
Imagine you wrote a useful calculate_average() function in one project. Now you need it in another project. Without modules, you copy-paste the function — and now you have two copies to maintain. Fix a bug in one, forget the other.
What is a module?
A module is a Python file that contains functions, variables, and classes you can use in other files. Every .py file you create is already a module. The only question is whether other files import it.
You have been using modules since Course 4:
import csv
import jsoncsv and json are modules that ship with Python. Someone wrote the functions inside them, and you import those functions into your own code. The mechanism is the same whether the module comes from Python, from a third-party package, or from a file you wrote yourself.
Why modules matter
Modules solve three problems:
- Organization — group related functions together. A
math_utils.pyfile holds math functions. Afile_helpers.pyfile holds file operations. Each file has one clear job. - Reuse — import a module into any project that needs it. Write once, use everywhere.
- Collaboration — team members work on separate modules without overwriting each other's code. Merge conflicts drop dramatically when responsibilities are split across files.
The Python import system
When you write import csv, Python searches for a file named csv.py (or a package named csv) in a specific order:
- The current directory
- The Python standard library
- Installed third-party packages
This search order matters. If you accidentally name your file csv.py, Python finds your file first and never reaches the real csv module. Avoid naming your files after built-in modules.
In this lesson, you will learn how to import existing modules, create your own, and structure code so other files can use it.