Why split your code?
A well-organised codebase gives you three concrete advantages:- Readability — each file has one clear job, so a new reader (including future-you) can find relevant code instantly
- Reusability — a
calculate_totalsfunction in its own module can be imported by multiple scripts without copy-pasting - Testability — small, focused functions with no side effects are trivial to unit-test; one giant script is nearly impossible to test reliably
Before: a single tangled script
Here is a realistic sales analysis script that does everything in one file. It works, but it is hard to maintain.Identify the logical groups
Read through your script and label every line with its responsibility. In the example above, four groups emerge naturally:After: four focused modules
Here is the project layout after refactoring:data_loader.py — reads and parses raw data
data_processor.py — all calculation logic
reporter.py — formatting and output
main.py — the orchestrator
main.py reads like plain English — it tells you what happens without burying you in how. The implementation details live in the appropriate modules.
Making your folder a package with __init__.py
Add an __init__.py to sales_analysis/ to make it a proper Python package. You can leave it empty, or use it to expose a clean public API:
Importing between modules
Use absolute imports within your package. They always resolve correctly, regardless of where you run the code from.-m flag:
Writing a simple test after refactoring
Once your logic lives in focused functions, writing tests becomes trivial. Createtests/test_data_processor.py:
analyzer.py and you will immediately understand why modular code is worth the refactoring effort.
Project Workflow
Learn the day-to-day workflow for managing Python projects end to end