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.
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.
Skills combined from Modules 1–9:
@dataclass& modern Type Hints (list[Expense],dict[str, float]) from Modules 7 & 8pathlib.Path&jsonpersistence with explicit UTF-8 encoding from Module 6defaultdict(float)category totals &sorted(key=...)ranking from Modules 4 & 5- Defensive validation (
ValueError), dependency injection, andif __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:
- Data Model (
Expense): A strongly typed@dataclassdefines the exact shape of every record so you never rely on fragile raw dictionary keys likerow["amnt"]. - Storage Layer (
load_expenses/save_expenses): Handles JSON serialization and disk I/O behind apath: Path = DATA_FILEparameter. Because the file path is injected rather than hardcoded, automated tests can point to a temporary directory without ever touching your realexpenses.json. - 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:
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'sjson.dumps()only serializes built-in types (dict,list,str,int,float,bool,None).asdict(e)turns eachExpenseinstance into a plain dict on save, and[Expense(**item) for item in raw]unpacks each dict back into a typedExpenseon load. - Boundary Normalization: Calling
category.strip().lower()insideadd_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): Storingdate.today().isoformat()makes dates human-readable in JSON and lexicographically sortable — meaningcreated_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.750000000000004in terminal output. (For real banking systems, upgradefloattodecimal.Decimalor 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:
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
5. Extension Challenges (Try Building These Yourself!)
- CLI Flags with
argparse: Add subcommands (add,list,summary,delete) and a--month 2026-11filter usinge.created_on.startswith(month). - CSV Export for Spreadsheets: Add an
export_csv(expenses, path)helper using Python's built-incsv.DictWriterso expenses open cleanly in Excel or Google Sheets. - Monthly Budget Alerts: Accept an optional
--budget 500threshold and print a warning banner whenever total monthly spend crosses 80% of the budget.
Quick Quiz: Module 10.1 — Expense Tracker Architecture
Keep Exploring: Related Lessons & Tools
All Courses →Validate, prettify, minify, sort keys, explore interactive collapsible JSON trees, and generate TypeScript interfaces instantly.
Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.