Intermediate level · Module 3: Modules, Packages and Virtual Environments · Lesson 2 of 3
Splitting Code into Your Own Modules
Move functions into separate files and import them, creating a clean project layout.
In this lesson you will
- Create and import your own modules
- Organise a small project into folders
Key concepts
modulepackage__init__.pyproject layout
The lesson
Every .py file is a module. When a program grows, move related functions into their own files — validators.py, io_helpers.py — and import them where needed: from validators import validate_phone.
Python finds your modules by looking in the folder of the script you run. Running from the wrong folder causes ModuleNotFoundError, so run the project from its top folder.
Modules make code easier to find, test and reuse. The if __name__ == "__main__": guard you learned earlier ensures that importing a module does not run its test code.
Step by step
- Create validators.py and move the validation functions into it.
- Create io_helpers.py for reading and writing files.
- Import both in main.py and run the program.
- Compare the output with the single-file version.
Practice activity
Split the CSV cleaner into validators.py, io_helpers.py and main.py and confirm it still works.
Expected result: A multi-file project that runs from main.py with unchanged output.
Check your understanding
-
Why split a growing program into modules?
Show answer
To group related code, make it easier to navigate and test, and reuse it in other programs.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.