Final project

Topic 4 of 4 in Tools and projects10 min readBeginnerFree course

Overview

Time to put everything together. In this project you’ll build expenses, a command-line expense tracker that you could genuinely use every day. It records what you spend, stores it in a JSON file, lists expenses, and prints a report by category with bar charts — and it comes with automated tests.

Along the way it uses almost every topic in the course: functions, dataclasses, dictionaries and lists, comprehensions, files and JSON, exceptions, argparse, modules and packages, type hints and pytest.

Final project: a command-line expense tracker. cli.py handles the argparse commands; tracker.py holds the Expense dataclass and the logic; storage.py loads and saves JSON to expenses.json; tests/ checks the logic with pytest. Example commands: python -m expenses add 12.50 food “Lunch” and python -m expenses report –month 2026-12, which prints food 212.40 and travel 86.00 with a bar for each. Uses: functions, dataclasses, dicts, files, JSON, errors, argparse, modules and tests.

What you’ll build

Text
$ python -m expenses add 12.50 food "Lunch" --date 2026-12-01
Added 12.50 for food on 2026-12-01
$ python -m expenses add 86 travel "Train to Leeds" --date 2026-12-02
Added 86.00 for travel on 2026-12-02
$ python -m expenses add 199.9 Food "Groceries" --date 2026-12-03
Added 199.90 for food on 2026-12-03

$ python -m expenses list --month 2026-12
2026-12-01  food          12.50  Lunch
2026-12-02  travel        86.00  Train to Leeds
2026-12-03  food         199.90  Groceries

$ python -m expenses report --month 2026-12
food         212.40  ████████████████████
travel        86.00  ████████
total        298.40

$ python -m expenses add -3 food
error: amount must be positive

Project layout

Text
expenses-project/
├── pyproject.toml
├── expenses/
│   ├── __init__.py
│   ├── __main__.py      ← makes "python -m expenses" work
│   ├── tracker.py       ← the Expense dataclass and calculations
│   ├── storage.py       ← load and save JSON
│   └── cli.py           ← argparse commands
└── tests/
    └── test_tracker.py  ← pytest tests

The design separates three layers:

  • tracker.py — the core logic. No printing, no files, no input(): just data in, data out. That makes it easy to test and reuse (a web or mobile version could use the same file).
  • storage.py — the only code that knows expenses live in a JSON file. Switching to CSV or a database would only touch this file.
  • cli.py — the only code that talks to the user. It parses arguments, calls the other layers, and prints.

Create the folders, then work through the files in this order. Set up a virtual environment and install pytest first:

Terminal
mkdir expenses-project && cd expenses-project
python -m venv .venv
source .venv/bin/activate          # Windows: .venv\Scripts\activate
python -m pip install pytest

Step 1: the model — tracker.py

Python
"""The core logic: what an expense is and how to summarise expenses."""

from dataclasses import dataclass
from datetime import date


@dataclass
class Expense:
    amount: float
    category: str
    description: str = ""
    day: str = ""  # ISO date, e.g. "2026-12-04"

    def __post_init__(self):
        if self.amount <= 0:
            raise ValueError("amount must be positive")
        self.amount = round(self.amount, 2)
        self.category = self.category.strip().lower()
        if not self.category:
            raise ValueError("category can't be empty")
        if not self.day:
            self.day = date.today().isoformat()
        date.fromisoformat(self.day)  # raises ValueError for a bad date


def in_month(expenses: list[Expense], month: str | None) -> list[Expense]:
    """Return the expenses in month ("YYYY-MM"), or all of them if month is None."""
    if month is None:
        return list(expenses)
    return [e for e in expenses if e.day.startswith(month + "-")]


def totals_by_category(expenses: list[Expense]) -> dict[str, float]:
    """Return {category: total}, largest first."""
    totals: dict[str, float] = {}
    for e in expenses:
        totals[e.category] = totals.get(e.category, 0) + e.amount
    return dict(sorted(totals.items(), key=lambda item: item[1], reverse=True))


def bar(value: float, largest: float, width: int = 20) -> str:
    """Return a bar of block characters proportional to value / largest."""
    if largest <= 0:
        return ""
    return "█" * round(value / largest * width)

What’s happening:

  • Expense is a dataclass (Dataclasses). __post_init__ validates and normalises every expense as it’s created — whether it’s typed on the command line or loaded from the file — so the rest of the program can trust the data. The date is stored as an ISO string, which sorts correctly as text and goes straight into JSON.
  • in_month filters with a list comprehension. Note the + "-": it makes sure "2026-1" can’t accidentally match October.
  • totals_by_category is the counting-with-a-dictionary pattern (Dictionaries), then sorts by total with a key (Functions as values).
  • bar turns a number into a text bar chart.

The amounts are floats, rounded to cents. That’s fine for a personal tracker; for real financial software you’d store whole cents as integers or use decimal.Decimal (Numbers and math).

Step 2: storage — storage.py

Python
"""Saving and loading expenses as JSON."""

import json
from dataclasses import asdict
from pathlib import Path

from .tracker import Expense


def load(path: Path) -> list[Expense]:
    """Return the expenses saved in path, or [] if the file doesn't exist yet."""
    try:
        with open(path, encoding="utf-8") as f:
            data = json.load(f)
    except FileNotFoundError:
        return []
    return [Expense(**item) for item in data]


def save(expenses: list[Expense], path: Path) -> None:
    """Write expenses to path as JSON."""
    with open(path, "w", encoding="utf-8") as f:
        json.dump([asdict(e) for e in expenses], f, indent=2)
  • asdict turns each Expense into a dict for JSON; Expense(**item) turns each dict back into an Expense — running the validation again.
  • A missing file isn’t an error on the first run, so it’s caught and treated as “no expenses yet” (Errors and exceptions).
  • from .tracker import Expense is a relative import within the package (Modules and imports).

Step 3: the interface — cli.py

Python
"""The command-line interface: parse arguments and call the logic."""

import argparse
import sys
from pathlib import Path

from . import storage
from .tracker import Expense, bar, in_month, totals_by_category


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(prog="expenses", description="Track your spending.")
    parser.add_argument("--file", type=Path, default=Path("expenses.json"),
                        help="where to store expenses (default: expenses.json)")
    commands = parser.add_subparsers(dest="command", required=True)

    add = commands.add_parser("add", help="record an expense")
    add.add_argument("amount", type=float)
    add.add_argument("category")
    add.add_argument("description", nargs="?", default="")
    add.add_argument("--date", default="", help="YYYY-MM-DD (default: today)")

    listing = commands.add_parser("list", help="show expenses")
    listing.add_argument("--month", help="only this month, as YYYY-MM")

    report = commands.add_parser("report", help="totals by category")
    report.add_argument("--month", help="only this month, as YYYY-MM")
    return parser


def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    expenses = storage.load(args.file)

    if args.command == "add":
        try:
            expense = Expense(args.amount, args.category, args.description, args.date)
        except ValueError as error:
            print(f"error: {error}", file=sys.stderr)
            return 1
        expenses.append(expense)
        storage.save(expenses, args.file)
        print(f"Added {expense.amount:.2f} for {expense.category} on {expense.day}")

    elif args.command == "list":
        for e in sorted(in_month(expenses, args.month), key=lambda e: e.day):
            print(f"{e.day}  {e.category:<10} {e.amount:>8.2f}  {e.description}")

    elif args.command == "report":
        totals = totals_by_category(in_month(expenses, args.month))
        if not totals:
            print("No expenses found.")
            return 0
        largest = max(totals.values())
        for category, total in totals.items():
            print(f"{category:<10} {total:>8.2f}  {bar(total, largest)}")
        print(f"{'total':<10} {sum(totals.values()):>8.2f}")

    return 0
  • Three subcommands — add, list, report — each with its own arguments (Command-line programs).
  • --file is a global option, so you can keep several files: python -m expenses --file holiday.json add 30 food.
  • Invalid input becomes a short message on stderr and exit code 1, not a traceback.
  • main() accepts an optional argv list, so you can drive the whole program from tests or the REPL: main(["report", "--month", "2026-12"]).

Step 4: wiring it up

Python
# expenses/__init__.py
"""A command-line expense tracker."""
Python
# expenses/__main__.py
import sys

from .cli import main

sys.exit(main())

__main__.py is what Python runs for python -m expenses. Passing main()’s return value to sys.exit sets the exit code.

Try it now from the expenses-project folder:

Terminal
python -m expenses add 12.50 food "Lunch"
python -m expenses report
python -m expenses --help
python -m expenses add --help

Step 5: tests — tests/test_tracker.py

Python
import pytest

from expenses import storage
from expenses.tracker import Expense, bar, in_month, totals_by_category


def test_category_is_cleaned_up():
    assert Expense(5, "  Food ", day="2026-12-01").category == "food"


@pytest.mark.parametrize("amount", [0, -12.5])
def test_amount_must_be_positive(amount):
    with pytest.raises(ValueError, match="positive"):
        Expense(amount, "food", day="2026-12-01")


def test_bad_date_is_rejected():
    with pytest.raises(ValueError):
        Expense(5, "food", day="2026-13-45")


def test_totals_by_month():
    expenses = [
        Expense(10, "food", day="2026-12-01"),
        Expense(25.5, "travel", day="2026-12-02"),
        Expense(4.5, "food", day="2026-12-03"),
        Expense(99, "food", day="2026-11-30"),
    ]
    december = in_month(expenses, "2026-12")
    assert totals_by_category(december) == {"travel": 25.5, "food": 14.5}


def test_bar_is_proportional():
    assert bar(50, 100, width=10) == "█" * 5
    assert bar(5, 0) == ""


def test_save_and_load_round_trip(tmp_path):
    path = tmp_path / "expenses.json"
    original = [Expense(12.5, "food", "Lunch", "2026-12-04")]
    storage.save(original, path)
    assert storage.load(path) == original


def test_missing_file_means_no_expenses(tmp_path):
    assert storage.load(tmp_path / "nothing.json") == []

And pyproject.toml, which tells pytest to import from the project folder:

TOML
[project]
name = "expenses"
version = "0.1.0"
requires-python = ">=3.10"

[tool.pytest.ini_options]
pythonpath = ["."]

Run them:

Text
$ pytest -q
........                                                        [100%]
8 passed in 0.01s

The tests cover normal cases, edge cases (an empty bar, a missing file) and error cases (negative amounts, impossible dates), and tmp_path keeps the storage test from touching your real data (Testing with pytest). Because the logic layer does no input or output, none of these tests needs to fake a terminal.

How the course topics fit together

Feature Lessons
Expense with validation Dataclasses, Raising exceptions, Type hints
Totals and filtering Dictionaries, Comprehensions, Functions as values
Report formatting Formatting output, String methods
JSON file Reading and writing files, CSV and JSON
Commands and options Command-line programs
Package and imports Modules and imports
Error handling Errors and exceptions
Test suite Testing with pytest

Ideas for going further

Once the exercise is done, keep building — this is how you really learn:

  • a delete command (give each expense an id) and an edit command;
  • export to CSV with csv.DictWriter, and import from your bank’s CSV export;
  • report --year 2026 with a month-by-month breakdown;
  • recurring expenses (rent, subscriptions) added automatically each month;
  • colours and tables with the rich package (install it in your venv);
  • a [project.scripts] entry in pyproject.toml, so pip install -e . gives you an expenses command;
  • store the data in SQLite with the sqlite3 module instead of JSON — only storage.py needs to change.

Congratulations

You’ve gone from print("Hello") to a tested, multi-module command-line application. You can now read and write real Python: work with data structures, functions and classes, handle files and errors, use the standard library and packages, and test your code.

Where to go next depends on what you want to build: web apps (FastAPI, Django, Flask), data analysis (pandas, Jupyter, matplotlib), automation (requests, playwright, scheduling scripts), or machine learning (scikit-learn, PyTorch). The fundamentals you’ve learned here are the same in every one of them.

Keep going: pick a small, real problem from your own life and solve it with Python. That project will teach you more than any tutorial.

Exercise

Add budgets to the tracker

Extend the finished tracker with budgets. In tracker.py, write parse_budgets(items), which turns a list like ["food=200", "travel=100"] into {"food": 200.0, "travel": 100.0} (lower-casing the categories and raising ValueError for items without =), and over_budget(totals, budgets), which returns a message such as food is 12.40 over its 200.00 budget for every category over its limit. In cli.py, add a repeatable --budget CATEGORY=AMOUNT option to the report command and print each warning after the totals (and a clean error for a malformed budget). Add tests for both functions. python -m expenses report --month 2026-12 --budget food=200 --budget travel=100 should end with Warning: food is 12.40 over its 200.00 budget.

Python
# ---- expenses/tracker.py: add these two functions ----
def parse_budgets(items: list[str]) -> dict[str, float]:
    """Turn ["food=200", "travel=100"] into {"food": 200.0, "travel": 100.0}."""
    ...


def over_budget(totals: dict[str, float], budgets: dict[str, float]) -> list[str]:
    """Return a warning for every category whose total is above its budget."""
    ...


# ---- expenses/cli.py: add a repeatable --budget option to the report command,
# ---- and print each warning after the totals

# ---- tests/test_tracker.py: add tests for both functions

Summary

  • Split a program into layers: the core logic (tracker.py), storage (storage.py) and the user interface (cli.py).
  • A package with __main__.py runs with python -m expenses; relative imports (from .tracker import …) connect its modules.
  • A dataclass with __post_init__ validation keeps bad data out of the whole program.
  • Keeping the logic free of input/output makes it easy to test with pytest — including storage, using tmp_path.
  • main(argv) returning an exit code keeps the command-line layer thin and testable.