Up Next: Testing and Quality

Module 3 gave you the tools of real programs (modules and packages, virtual environments, exceptions and the debugger, text, CSV and JSON files, and classes); this lesson shows which tool fits which job, a contact manager you can build with all of them, and what Module 4 adds.

Apprentice · Python · Updated

By

After this lesson you can

  • Choose the Module 3 tool that fits a job, such as a module, a virtual environment, try and except, a CSV or JSON file, or a class

Key takeaways

  • Modules split a program into files, and a virtual environment keeps each project's packages to itself.
  • try and except let a program carry on after an error it expected, and the debugger shows what your code is really doing.
  • CSV files hold tables and JSON files hold a program's data between runs, and classes and dataclasses describe your own kinds of things.
  • Module 4 proves your code works with pytest tests, and keeps it tidy with type hints, mypy and Ruff.

You've finished the module where your programs start to look like real ones. They're split into files, they install the packages they need, they cope with bad input, they read and write files, and they describe their own kinds of things with classes. This lesson puts those tools side by side, shows a program you can build with all of them, and gives you a first look at Module 4.

What you can do now

The tool What it's for Where you used it
import, your own modules and packages Splitting a program into files that each do one job, and using the standard library Exercise: Game Night Toolkit
A virtual environment and pip Giving each project its own packages, pinned in requirements.txt Exercise: Game Night Toolkit
try, except and raise Carrying on after an error you expected, and stopping with a clear message Exercise: Parking Kiosk
The debugger Pausing a program to watch its values change, line by line Finding Bugs with the Debugger
open(), csv and json Reading and writing text, tables and a program's saved data Exercise: Running Club Log
Classes, dataclasses and inheritance Describing your own kinds of things, with their data and what they can do Exercise: Houseplant Care

Which tool fits?

When you plan a program, each part of the job points to a tool:

  • A file that's grown too long, or code another program could use: split it into modules and import them.
  • A package someone else wrote, such as pytest: install it with pip, inside the project's virtual environment, and pin its version in requirements.txt.
  • Input that might be wrong, such as two typed where a number belongs: catch the error with try and except, and say what to type instead.
  • A rule your code must refuse to break, such as negative hours: raise an exception with a message that says why.
  • A wrong answer with no error message: set a breakpoint and step through it with the debugger.
  • A table of rows and columns, such as a spreadsheet's export: a CSV file, read with csv.DictReader.
  • A program's own data, kept between runs: a JSON file, written with json.dump and read back with json.load.
  • One kind of thing with its own data and rules: a class, a dataclass when it mainly holds data, and a subclass for a kind that differs in a few ways.

Build it yourself: a contact manager

Here's a program that puts the whole module to work, and you can build it now, on your own: a contact manager that runs in the terminal.

  • a menu that repeats until the user quits: add a contact, list them all, search by name, delete one;
  • a Contact dataclass for each person's name, phone number and email;
  • the contacts saved to contacts.json after every change, and loaded again when the program starts, so nothing is lost between runs;
  • a missing or damaged contacts.json handled with a friendly message instead of a traceback;
  • bad menu choices refused, with the menu shown again;
  • the code split into modules: one for the contacts, one for saving and loading, and one for the menu.

The trickiest part is the trip to JSON and back, because JSON knows about lists, dictionaries, text and numbers, but not your dataclass. Each contact becomes a dictionary on the way out, and a Contact again on the way in:

import json
from dataclasses import dataclass


@dataclass
class Contact:
    name: str
    phone: str


contacts = [Contact("Maya", "555-0142"), Contact("Leo", "555-0187")]
text = json.dumps([{"name": c.name, "phone": c.phone} for c in contacts])
print(text)

loaded = [Contact(row["name"], row["phone"]) for row in json.loads(text)]
print(loaded[1])
print(loaded == contacts)
[{"name": "Maya", "phone": "555-0142"}, {"name": "Leo", "phone": "555-0187"}]
Contact(name='Leo', phone='555-0187')
True

json.dumps turns the list of dictionaries into JSON text, and json.loads turns the text back into dictionaries. The dataclass's own == proves the trip lost nothing. In the real program, json.dump and json.load write that text to contacts.json and read it back, as JSON Files: Saving Your Data shows.

Up next: proving your code works

So far, you've found out whether your code works by running it and reading what it prints, and the exercises came with tests someone else wrote. Module 4 hands you that power. A test is a small function that calls your code and checks the answer with assert, which stops the program when its condition is false:

from datetime import date


def days_between(first, second):
    return (second - first).days


def test_days_between():
    assert days_between(date(2026, 5, 7), date(2026, 5, 10)) == 3
    assert days_between(date(2026, 5, 10), date(2026, 5, 10)) == 0


test_days_between()
print("Both checks passed")
Both checks passed

Here the last lines call the test by hand. pytest, the tool every exercise has used, finds every function whose name starts with test_, runs them all and reports each one that fails. Module 4 teaches you to write those tests yourself, including the edge cases where bugs hide, and then to keep code tidy: type hints (you've written some already, such as name: str in a dataclass), mypy to check them, and Ruff to format your code and point out mistakes before you run it.

Check yourself

2 questions to try on the lesson page.

So what

Your programs now save their work, survive bad input and describe their own things. Module 4 is how you prove they keep working as they grow.

Key terms

Related