The capstone is a small program that is complete in every part. It is a command-line tool that records expenses in a JSON file and then reports on them. It uses a dataclass for the record, a separate module for file storage, argparse for the interface, and a package layout that keeps every layer testable on its own.
The previous lesson in this module covered "Threading vs asyncio: Choosing Concurrency", and this lesson is the last one in the Python Testing, Multithreading and a Capstone Project module.
What does the finished tool do?
It has four commands, and each one of them is obvious. You can add an expense, you can list what is stored, you can remove one by its id, and you can summarise the totals per category. The data lives in a plain JSON file that you can open in any text editor.
python -m ledger add --amount 12.50 --category food --note "lunch"
python -m ledger add --amount 3.20 --category transport --note "bus fare"
python -m ledger add --amount 45.00 --category food --note "weekly shop"
python -m ledger add --amount 120.00 --category utilities --note "internet"
python -m ledger list
python -m ledger list --category food
python -m ledger summary
python -m ledger remove --id 2
Here is what those commands actually printed when this project was run.
added #1 12.50 in food
added #2 3.20 in transport
added #3 45.00 in food
added #4 120.00 in utilities
#1 2026-10-27 12.50 food lunch
#2 2026-10-27 3.20 transport bus fare
#3 2026-10-27 45.00 food weekly shop
#4 2026-10-27 120.00 utilities internet
4 entries
food 57.50
transport 3.20
utilities 120.00
total 180.70
The date on each line is the day that the command ran. The numbers come straight out of the JSON file, so the tool can be used from the shell, from a cron job, or from another Python script that imports the package.
How is the project laid out?
ledger/
├── __init__.py # marks the folder as a package
├── __main__.py # python -m ledger starts here
├── models.py # what an expense is
├── storage.py # reading and writing the JSON file
├── commands.py # add, list, remove, summarise
└── cli.py # argument parsing and printing
Each file answers one question. models.py says what the data looks like. storage.py says how it is saved. commands.py says what the tool is able to do. cli.py says how the user asks for it. The dependencies point one way only. The CLI knows about the commands, the commands know about the storage and the models, and the models know about nothing except the standard library.
That is the arrangement from the previous lesson about splitting a program across several files, applied to something that you would actually ship. A test for the totals does not need to touch the disk, and a test for the CLI does not need to know how the file is stored.
The file that you cannot see in the listing is commands.py, and it holds the four operations. There is add_expense, list_expenses, remove_expense, and totals_by_category. Each one takes a path and returns plain data, and each one is short enough to read in one breath. Keeping them out of cli.py is what lets you call them from a script, from a notebook, or from a test without going through argparse.
How does an expense survive a round trip through JSON?
The record is a dataclass, and the two methods that matter are to_dict and from_dict. They are the only place where the shape in memory and the shape on disk meet each other.
# ledger/models.py
"""The Expense record and how it is converted to and from plain data."""
from dataclasses import asdict, dataclass
from datetime import date
@dataclass
class Expense:
"""A single expense entry."""
id: int
amount: float
category: str
note: str = ""
day: str = ""
def __post_init__(self):
"""Fill in today's date when the caller did not supply one."""
if not self.day:
self.day = date.today().isoformat()
def to_dict(self):
"""Return the record as a plain dictionary."""
return asdict(self)
@classmethod
def from_dict(cls, data):
"""Build an Expense from a dictionary read from JSON."""
return cls(
id=int(data["id"]),
amount=float(data["amount"]),
category=str(data["category"]),
note=str(data.get("note", "")),
day=str(data.get("day", "")),
)
Two details make this safe to use. The conversions inside from_dict are explicit, with int(...), float(...), and str(...), so a JSON file that was written by hand with "amount": "12.50" still loads as a number. And .get(...) with a default means that an old file from before the note field existed still loads instead of raising KeyError.
How does the file layer stay separate?
Storage is two functions and a path. Neither of the functions knows what an expense means, and neither of them prints anything.
# ledger/storage.py
"""Reading and writing the JSON file that holds the expenses."""
import json
from pathlib import Path
from .models import Expense
DEFAULT_PATH = Path("ledger-data") / "expenses.json"
def load(path=DEFAULT_PATH):
"""Return every expense stored in the JSON file."""
if not path.exists():
return []
raw = json.loads(path.read_text(encoding="utf-8"))
expenses = []
for item in raw:
expenses.append(Expense.from_dict(item))
return expenses
def save(expenses, path=DEFAULT_PATH):
"""Write every expense back to the JSON file."""
path.parent.mkdir(parents=True, exist_ok=True)
payload = []
for expense in expenses:
payload.append(expense.to_dict())
path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
def next_id(expenses):
"""Return the next free id for the list."""
biggest = 0
for expense in expenses:
if expense.id > biggest:
biggest = expense.id
return biggest + 1
Three things in there earn their place. The line path.parent.mkdir(parents=True, exist_ok=True) creates the data folder on first use, so the tool works on a fresh checkout with no setup step at all. The load function returns an empty list for a file that does not exist, which means that "no expenses yet" and "the file is missing" are the same situation for the rest of the program. And indent=2 keeps the file readable, because a data file that you cannot read is a data file that you cannot repair by hand.
How does argparse build the interface?
argparse gives you a parser, a set of subcommands, and a help screen for free. The trick is to build the parser inside its own function, so that the rest of the module never touches the argument objects.
# ledger/cli.py - excerpt
"""The command line interface of the ledger tool."""
import argparse
from . import commands
from .storage import DEFAULT_PATH
def build_parser():
"""Build the argument parser for every command."""
parser = argparse.ArgumentParser(
prog="ledger",
description="Track expenses in a JSON file.",
)
parser.add_argument("--data", default=None, help="path to the JSON data file")
sub = parser.add_subparsers(dest="command", required=True)
add = sub.add_parser("add", help="add an expense")
add.add_argument("--amount", type=float, required=True, help="amount spent")
add.add_argument("--category", required=True, help="category such as food or travel")
add.add_argument("--note", default="", help="optional note")
listing = sub.add_parser("list", help="list the stored expenses")
listing.add_argument("--category", default=None, help="only show this category")
remove = sub.add_parser("remove", help="remove an expense by id")
remove.add_argument("--id", type=int, required=True, help="id of the expense to remove")
sub.add_parser("summary", help="show the totals per category")
return parser
type=float and type=int do the validation for you. The argument is converted before your own code sees it, and a bad value is rejected with a usage message instead of a traceback. Putting required=True on the subparsers means that running python -m ledger with no command at all prints the help text instead of doing nothing.
Then main dispatches on the command name and returns an exit code. Returning 1 for "no expense with that id" is what lets a shell script react to a failure, and it is the reason that this tool can be used inside other automation.
Notice that main prints, but it does not decide. The formatting of a row, with its padding, its column widths, and its # prefix, lives in the printing code, while the decisions about what to print live in commands.py. That separation is what keeps a change to the output format from ever touching the storage layer.
What does the JSON file look like?
Because the storage is plain JSON, you can read the file with anything at all, including a five-line Python script that does not import your own package.
import json
from pathlib import Path
records = json.loads(Path("ledger-data/expenses.json").read_text(encoding="utf-8"))
for record in records:
print('#' + str(record['id']), record['day'], record['amount'], record['category'])
The same trick works for the totals, and that is a good way to check that the tool and the file agree with each other.
import json
from pathlib import Path
records = json.loads(Path("ledger-data/expenses.json").read_text(encoding="utf-8"))
totals = {}
for record in records:
category = record["category"]
if category in totals:
totals[category] = totals[category] + record["amount"]
else:
totals[category] = record["amount"]
grand_total = 0.0
for category in sorted(totals):
print(category, totals[category])
grand_total = grand_total + totals[category]
print('total', grand_total)
Two design choices make this file safe to grow. Nothing is written until a command asks for it, so a typo in a command name cannot damage the data. And every write replaces the whole file instead of adding to the end of it, which means that there is exactly one version of the truth on disk. If you want a history of changes, that is a different design, and it deserves a different file format.
What to remember
- Split a program by responsibility, into a model, a storage layer, the commands, and the interface, and let the dependencies point one way.
- Use a dataclass with
to_dictandfrom_dictas the only bridge between your objects and JSON. - Keep the file paths in one module, so that the rest of the program never hard-codes a filename.
- Let
argparsehandle the types, the required arguments, and the help screen. - Return meaningful exit codes, and keep the stored format plain enough to read with any other tool.
Try it yourself: Copy this project and run it from end to end. Then extend it in three steps. First, add a --month filter to the list command and a --month option to summary. Second, add a total column to the summary output that includes a fixed 20 percent tax. Third, write three pytest tests: one that checks that add_expense assigns the next free id, one that checks that remove_expense returns False for an unknown id, and one that checks that totals_by_category sums two expenses in the same category. Use the tmp_path fixture in each one so that no test ever touches the real data file.