One file works right up until the moment that it stops working. As soon as a script holds two unrelated ideas, the right move is to split it, but where the lines fall matters much more than the number of files that you end up with. This guide takes a working single-file program, pulls it apart, and shows you the rules that keep the result easy to navigate.
This is the first lesson in the Python Testing, Multithreading and a Capstone Project module, and the next lesson in this module is about "Writing Your First Tests with pytest".
When does a single file stop being enough?
The size of the file is a poor signal. A two-thousand-line file of generated data and a two-thousand-line file of unrelated business rules are not the same problem at all. The signal that matters is change. If one part of the file changes every week and another part has not changed since the day you wrote it, then those are two modules that happen to share one filename.
Four concrete symptoms tell you that it is time to split.
- Two sections of the file never need each other, but you scroll past each other constantly.
- You keep copy-pasting a helper into another script, and the copies slowly drift apart.
- The same name means two different things in two different parts of the file.
- You cannot write a test for one part without importing the side effects of the other part.
The last symptom is the strongest one of the four. A file that has to be executed before it is useful cannot be tested piece by piece, and code that cannot be tested stays broken for a very long time.
Where should the split lines go?
The rule that works most often is short: one module, one reason to change. Data shapes live with each other, business rules live together, and input and output handling sits at the edges. Here is the single-file program that we are about to break up.
# shifts.py - everything lives in one file
from dataclasses import dataclass
from datetime import date
@dataclass(frozen=True)
class Shift:
"""A single shift worked by a team member."""
person: str
day: date
hours: float
SHIFTS = [
Shift("ada", date(2026, 10, 5), 8),
Shift("ada", date(2026, 10, 6), 9.5),
Shift("grace", date(2026, 10, 6), 7),
Shift("grace", date(2026, 10, 7), 8),
Shift("linus", date(2026, 10, 6), 10),
]
def total_hours(shifts):
"""Return the total number of hours worked."""
total = 0.0
for shift in shifts:
total = total + shift.hours
return total
def hours_by_person(shifts):
"""Return the hours worked by each person."""
totals = {}
for shift in shifts:
if shift.person in totals:
totals[shift.person] = totals[shift.person] + shift.hours
else:
totals[shift.person] = shift.hours
return totals
def busiest_day(shifts):
"""Return the day with the most hours, or None when there are no shifts."""
totals = {}
for shift in shifts:
if shift.day in totals:
totals[shift.day] = totals[shift.day] + shift.hours
else:
totals[shift.day] = shift.hours
if not totals:
return None
best_day = None
best_total = 0.0
for day, hours in totals.items():
if hours > best_total:
best_day = day
best_total = hours
return best_day
for person, hours in sorted(hours_by_person(SHIFTS).items()):
print(' ', person, ' ', hours)
print(len(SHIFTS), 'shifts,', total_hours(SHIFTS), 'hours total')
Three different things are tangled together in that file. The Shift record, the calculations, and the printing. The printing at the bottom is the most important part of the problem, because it is the reason that the file can only be tested by running it.
Splitting is not the same thing as making files smaller. If you break the program into three files of roughly equal length, you have made it harder to read, because now the reader has to open three files to follow one idea. Split along the seams that already exist in the problem. That means the data shape, the rules, the presentation, and the entry point.
Sample data deserves its own mention. In the original file the list of shifts sits in the middle of the program, so importing the file for its functions also imports the data. Moving that list into the entry point keeps the data next to the decision to use it, and that is what makes the rest of the package reusable from a different script tomorrow.
What does the split program look like?
It is four files, each with one job, inside a package folder that holds them.
shiftplan/
├── __init__.py # empty - it marks the folder as a package
├── models.py # the Shift record
├── scheduler.py # the calculations
├── report.py # turning the results into text
└── __main__.py # the entry point
# shiftplan/models.py
"""The data types that the planner works with."""
from dataclasses import dataclass
from datetime import date
@dataclass(frozen=True)
class Shift:
"""A single shift worked by a team member."""
person: str
day: date
hours: float
@property
def is_long(self) -> bool:
"""Return True when the shift runs longer than eight hours."""
return self.hours > 8
# shiftplan/scheduler.py
"""Pure calculations over a list of shifts."""
from .models import Shift
def total_hours(shifts):
"""Return the total number of hours worked."""
total = 0.0
for shift in shifts:
total = total + shift.hours
return total
def hours_by_person(shifts):
"""Return the hours worked by each person."""
totals = {}
for shift in shifts:
if shift.person in totals:
totals[shift.person] = totals[shift.person] + shift.hours
else:
totals[shift.person] = shift.hours
return totals
def busiest_day(shifts):
"""Return the day with the most hours, or None when there are no shifts."""
totals = {}
for shift in shifts:
if shift.day in totals:
totals[shift.day] = totals[shift.day] + shift.hours
else:
totals[shift.day] = shift.hours
if not totals:
return None
best_day = None
best_total = 0.0
for day, hours in totals.items():
if hours > best_total:
best_day = day
best_total = hours
return best_day
# shiftplan/report.py
"""Turning a schedule into text that people can read."""
from .scheduler import hours_by_person, total_hours
def render(shifts):
"""Return a readable report of the schedule."""
lines = [str(len(shifts)) + ' shifts, ' + str(total_hours(shifts)) + ' hours total']
for person, hours in sorted(hours_by_person(shifts).items()):
lines.append(' ' + person + ' ' + str(hours))
return '\n'.join(lines)
# shiftplan/__main__.py
"""Run the planner demo with: python -m shiftplan"""
from datetime import date
from .models import Shift
from .report import render
from .scheduler import busiest_day
SAMPLE = [
Shift("ada", date(2026, 10, 5), 8),
Shift("ada", date(2026, 10, 6), 9.5),
Shift("grace", date(2026, 10, 6), 7),
Shift("grace", date(2026, 10, 7), 8),
Shift("linus", date(2026, 10, 6), 10),
]
def main():
"""Print the sample schedule."""
print(render(SAMPLE))
day = busiest_day(SAMPLE)
if day is None:
print('busiest day: none')
else:
print('busiest day:', day.isoformat())
if __name__ == "__main__":
main()
Run it with python -m shiftplan from the folder that contains the package. The report and the busiest day come from exactly the same data as before, and now the calculations can be tested without printing anything at all.
python -m shiftplan
The output shows five shifts and 42.5 hours, with ada on 17.5 hours and grace on 15.0 hours. The busiest day is the 6th, because three people worked on it.
How do you keep the import graph healthy?
The rule is one-directional. The entry point knows about everything, the report knows about the calculations, the calculations know about the data types, and the data types know about nobody at all. Nothing points back up the chain, so the graph cannot contain a cycle.
import ast
from pathlib import Path
for path in sorted(Path("shiftplan").glob("*.py")):
tree = ast.parse(path.read_text(encoding="utf-8"))
imported = []
for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom) and node.level == 1:
imported.append(node.module)
print(path.name, 'imports', imported)
Run from the folder that holds the package, this prints the relative imports of every module. report.py imports from models and scheduler, scheduler.py imports from models, and models.py imports from nothing at all. That is the shape that you want, and a script like this one tells you in a few seconds when a new import breaks the pattern.
Two habits keep the graph clean. Modules that contain calculations should take plain data and return plain data, so that they can be tested without touching the filesystem or the network. And the module that knows about the outside world, which is the entry point, is the only one that is allowed to read input and to print output.
Which file is the entry point?
One file per program owns the start. For a package that file is __main__.py, and python -m shiftplan runs it. For a script, the file that you invoke with python file.py is the entry point, and the if __name__ == "__main__": guard keeps the rest of that file importable.
Two habits make the difference between a program and a library. Put the sample data in the entry point rather than in a data module, so that importing the package has no side effects at all. And keep the entry point thin. It wires things together and it calls functions, but it contains no calculations of its own.
Names are part of the structure too. scheduler.py tells a reader what lives inside it before they even open it, while utils.py or helpers.py tells them nothing at all. When two modules need similar names, that is usually a sign that one of them is missing a concept of its own. A pricing.py and a billing.py are two separate ideas, whereas a utils.py is simply a drawer for the things that nobody has managed to name yet.
Quick reference
- Split when the parts of a file change for different reasons, and not when the file simply gets long.
- Give every module one reason to change: data types, rules, presentation, or the entry point.
- Keep the import graph acyclic and pointing downwards, from the entry point to the data types.
- Calculations take data and return data, and that is exactly what makes them testable.
- Give the package a
__main__.pyand run it withpython -m shiftplan.
Try it yourself: Take the single-file program on this page and split it exactly as shown. Then split it in a different way. Move the printing into a render.py and the sample data into a sample_data.py, and then decide which of the two layouts you would rather work in. Finally, write a test that calls busiest_day with an empty list and checks that it returns None. If that test is easy to write, then the split worked properly.