Python · Module 10: Hands-On Mini-ProjectsTutorial 29 of 30
All Tutorials·~2.5 hrs

10.1 Project 1: Persistent CLI Expense Tracker

Put Modules 1–9 together! Build a clean, persistent JSON-backed Expense Tracker CLI from scratch with dataclasses, validation, category summaries, and automated pytest tests.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. What You Will Build & Architecture Blueprint

Instead of toy snippets, let's build a real, portfolio-ready CLI tool (expense_tracker.py) that persists expenses to disk in JSON, rejects invalid inputs at the boundary, and aggregates spending by category.

Visual: Clean Real-World Python Project Architecture (Separation of Concerns)
1. Input / CLIArgs, User Prompt2. Models@dataclass + Types3. Core LogicPure Functions + Tests4. Storage / APIJSON / HTTP + Errors

Skills combined from Modules 1–9:

  • @dataclass & modern Type Hints (list[Expense], dict[str, float]) from Modules 7 & 8
  • pathlib.Path & json persistence with explicit UTF-8 encoding from Module 6
  • defaultdict(float) category totals & sorted(key=...) ranking from Modules 4 & 5
  • Defensive validation (ValueError), dependency injection, and if __name__ == "__main__": guards from Modules 6 & 9

Why This Architecture Scales Cleanly

Notice how the program is split into three clean layers instead of one giant script full of input() and print() calls:

  1. Data Model (Expense): A strongly typed @dataclass defines the exact shape of every record so you never rely on fragile raw dictionary keys like row["amnt"].
  2. Storage Layer (load_expenses / save_expenses): Handles JSON serialization and disk I/O behind a path: Path = DATA_FILE parameter. Because the file path is injected rather than hardcoded, automated tests can point to a temporary directory without ever touching your real expenses.json.
  3. Pure Business Logic (add_expense / summarize_by_category): Operates strictly on in-memory Python objects with zero disk or console side effects — making it trivial to test, reuse in a FastAPI backend, or export to CSV later.

2. Complete Runnable Code (expense_tracker.py)

Save this file locally and run python3 expense_tracker.py:

PYTHON
from collections import defaultdict
from dataclasses import asdict, dataclass
from datetime import date
import json
from pathlib import Path

DATA_FILE = Path("expenses.json")

@dataclass
class Expense:
    title: str
    category: str
    amount: float
    created_on: str

def load_expenses(path: Path = DATA_FILE) -> list[Expense]:
    if not path.exists():
        return []
    raw = json.loads(path.read_text(encoding="utf-8"))
    return [Expense(**item) for item in raw]

def save_expenses(expenses: list[Expense], path: Path = DATA_FILE) -> None:
    payload = [asdict(e) for e in expenses]
    path.write_text(json.dumps(payload, indent=2), encoding="utf-8")

def add_expense(expenses: list[Expense], title: str, category: str, amount: float) -> Expense:
    if not title.strip():
        raise ValueError("Expense title cannot be empty.")
    if amount <= 0:
        raise ValueError("Expense amount must be greater than 0.")
    item = Expense(
        title=title.strip(),
        category=category.strip().lower(),
        amount=round(amount, 2),
        created_on=date.today().isoformat(),
    )
    expenses.append(item)
    return item

def summarize_by_category(expenses: list[Expense]) -> dict[str, float]:
    totals: dict[str, float] = defaultdict(float)
    for e in expenses:
        totals[e.category] += e.amount
    return {k: round(v, 2) for k, v in sorted(totals.items(), key=lambda x: x[1], reverse=True)}

if __name__ == "__main__":
    items = load_expenses()
    add_expense(items, "Coffee", "Food", 4.50)
    add_expense(items, "Metro Pass", "Travel", 15.00)
    add_expense(items, "Lunch", "Food", 12.25)
    save_expenses(items)

    print("Spending Summary:")
    for cat, total in summarize_by_category(items).items():
        print(f"  {cat.title():10s} : ${total:.2f}")

Engineering Details Worth Noticing

  • JSON Round-Tripping with asdict() & **item: Python's json.dumps() only serializes built-in types (dict, list, str, int, float, bool, None). asdict(e) turns each Expense instance into a plain dict on save, and [Expense(**item) for item in raw] unpacks each dict back into a typed Expense on load.
  • Boundary Normalization: Calling category.strip().lower() inside add_expense() guarantees that "Food", "food", and " FOOD " merge into a single "food" bucket instead of fragmenting your spending report.
  • ISO-8601 Dates (YYYY-MM-DD): Storing date.today().isoformat() makes dates human-readable in JSON and lexicographically sortable — meaning created_on.startswith("2026-11") filters an entire month without parsing timestamps!
  • Floating-Point Guardrails: Rounding totals with round(v, 2) prevents ugly IEEE-754 artifacts like $16.750000000000004 in terminal output. (For real banking systems, upgrade float to decimal.Decimal or integer cents.)

3. Verifying Your Project with pytest & tmp_path

Connect what you learned in Module 9.3 by adding test_expense_tracker.py right beside expense_tracker.py. Notice how pytest's built-in tmp_path fixture lets us test real disk persistence safely in under 10 milliseconds:

PYTHON
import pytest
from expense_tracker import add_expense, load_expenses, save_expenses, summarize_by_category

def test_save_and_load_round_trip(tmp_path):
    test_file = tmp_path / "test_expenses.json"
    items = []
    add_expense(items, "Coffee", " Food ", 4.50)
    add_expense(items, "Lunch", "food", 12.25)
    save_expenses(items, path=test_file)

    reloaded = load_expenses(path=test_file)
    assert len(reloaded) == 2
    assert summarize_by_category(reloaded) == {"food": 16.75}

def test_negative_amount_rejected():
    with pytest.raises(ValueError, match="greater than 0"):
        add_expense([], "Invalid", "misc", -5.0)

4. Interactive Trace: Adding & Aggregating Expenses

Tracing Category Aggregation in summarize_by_category()
Interactive Line-by-Line Execution Trace · Step 1 of 5
1→totals = defaultdict(float)
2for e in [Expense("Coffee", "food", 4.5), Expense("Metro", "travel", 15.0), Expense("Lunch", "food", 12.25)]:
3 totals[e.category] += e.amount
4print(dict(totals))
Variables in Memory
totals{}defaultdict
Console Output
(nothing printed yet)
What just happened: defaultdict(float) automatically initializes any unseen category key to 0.0!

5. Extension Challenges (Try Building These Yourself!)

  1. CLI Flags with argparse: Add subcommands (add, list, summary, delete) and a --month 2026-11 filter using e.created_on.startswith(month).
  2. CSV Export for Spreadsheets: Add an export_csv(expenses, path) helper using Python's built-in csv.DictWriter so expenses open cleanly in Excel or Google Sheets.
  3. Monthly Budget Alerts: Accept an optional --budget 500 threshold and print a warning banner whenever total monthly spend crosses 80% of the budget.

Quick Quiz: Module 10.1 — Expense Tracker Architecture

Q1.Why did we pass `path: Path = DATA_FILE` as a parameter to `load_expenses()` instead of hardcoding `DATA_FILE` inside the function?
Q2.What does `dataclasses.asdict(e)` do before `json.dumps()`?
Q3.Why did we normalize `category.strip().lower()` when creating an Expense?

Keep Exploring: Related Lessons & Tools

All Courses →