Build a small command-line habit tracker in Python, stage by stage: a typed data model, validation with clear errors, JSON files on disk read by a generator, a weekly report with streaks, an argparse interface and a set of plain-assert tests.
17 min read0/5 questions
You have spent this unit learning how a real Python project is laid out, tested and kept safe. This lesson puts that to work on something small enough to finish and real enough to keep using. You will build habits, a command-line tool that tracks daily habits like reading or running, saves them to files, and prints a weekly report with streaks.
It touches most of what a Python job needs: a data model, untrusted input, files, date maths, a command-line interface and tests. Each stage below is a complete program in its own runnable block. Every block repeats the code it needs from earlier stages, so you can run any of them alone. They run in your browser with a temporary file system, so the file code works for real.
The plan: files at the edge, plain data in the middle
The design has one rule: anything that comes from a file or the command line is checked once, at the edge, and turned into a typed object. After that, the logic never checks types again. It works with frozen dataclasses and returns plain values, which is what makes it easy to test.
How a check-in flows through the tracker
argparse turns the command line into an object with attributes. It knows nothing about habits.
1/4
The app keeps two files. habits.json holds the list of habits and how many days a week you aim for. checkins.jsonl is a log: one line per check-in, only ever appended to. The habit list is small and rewritten whole. The log grows forever and is never rewritten.
Stage 1: the data model
Start with the nouns. A Habit has a name and a weekly target. A CheckIn says which habit you did, on which day, with an optional note. Both are dataclasses from Dataclasses, with two options worth copying into real projects:
frozen=True makes instances read-only, so nothing changes a record after it is created. It also makes them hashable, so you can put them in sets and use them as dict keys, as Tuples and Sets explained.
slots=True saves memory and turns a typo like c.dya = ... into an error.
The day is a real date, not a string, because you cannot subtract strings. Convert at the edge, use real types inside. The hints from Type Hints let a type checker hold you to it.
from dataclasses import FrozenInstanceError, dataclassfrom datetime import date@dataclass(frozen=True, slots=True)class Habit: name: str per_week: int # how many days a week you aim for@dataclass(frozen=True, slots=True)class CheckIn: habit: str day: date note: str = ""read = Habit("read", per_week=5)log = [ CheckIn("read", date(2026, 10, 21)), CheckIn("read", date(2026, 10, 22), note="two chapters"), CheckIn("read", date(2026, 10, 22)), # same day, different note]print(read)print(log[1])print("Same day twice equal?", log[1] == log[2])print("Unique days:", sorted({c.day for c in log}))try: read.per_week = 7except FrozenInstanceError as e: print("Blocked:", e)
Output
Press Run (⌘ Enter) to see what happens.
Two check-ins on the same day with different notes are not equal, because the generated __eq__ compares every field. That is correct for the log, but the report will care about days, not records. The set comprehension on the last lines shows the fix you will use later: build a set of days, and duplicates disappear.
Check: the output shows two unique days, and the assignment to per_week is blocked.
Quick check
Why does {c.day for c in log} work, while {c for c in log} would fail if CheckIn were a plain @dataclass without frozen=True?
Need a nudge? A hint rules out a wrong answer.
Stage 2: validation and errors
Records will come from two places you do not control: a JSON file a person might edit by hand, and the command line. So the next piece is a pair of parsers that take a raw value and return a Habit or a CheckIn, or raise an error that says exactly what is wrong.
The errors follow Errors and Exceptions. The app defines one base class, TrackerError, for every error it raises on purpose, and a more specific InvalidRecord under it. The command line will catch TrackerError in one place and print a friendly message. Anything else, like a bug in your code, still shows a full traceback.
The parsers use match with mapping patterns from Structural Pattern Matching. A pattern like {"habit": str(habit), "day": str(day), **rest} checks that the value is a mapping, that both keys exist, and that both values are strings, all in one line. A guard like if 1 <= n <= 7 adds a range check. Habit names are checked with fullmatch from Regular Expressions.
Look at how a bad date is handled. date.fromisoformat raises ValueError, and the parser re-raises it as InvalidRecord with raise ... from e. The caller gets one exception type to catch, and the original error is kept in __cause__ for debugging.
import refrom dataclasses import dataclassfrom datetime import dateNAME = re.compile(r"[a-z][a-z0-9-]{0,29}")@dataclass(frozen=True, slots=True)class Habit: name: str per_week: int@dataclass(frozen=True, slots=True)class CheckIn: habit: str day: date note: str = ""class TrackerError(Exception): """Base class for every error this app raises on purpose."""class InvalidRecord(TrackerError): """A record from a file or the command line is not valid."""def check_name(name: str) -> str: if not NAME.fullmatch(name): raise InvalidRecord(f"bad habit name {name!r}: use a-z, 0-9 and -") return namedef parse_habit(raw: object) -> Habit: match raw: case {"name": str(name), "per_week": int(n)} if 1 <= n <= 7: return Habit(check_name(name), n) case {"name": str(), "per_week": int()}: raise InvalidRecord("per_week must be between 1 and 7") case _: raise InvalidRecord(f"not a habit: {raw!r}")def parse_checkin(raw: object) -> CheckIn: match raw: case {"habit": str(habit), "day": str(day), **rest}: try: parsed = date.fromisoformat(day) except ValueError as e: raise InvalidRecord(f"bad day {day!r}") from e note = rest.get("note", "") if not isinstance(note, str): raise InvalidRecord("note must be text") return CheckIn(check_name(habit), parsed, note) case _: raise InvalidRecord(f"not a check-in: {raw!r}")samples = [ {"habit": "read", "day": "2026-10-22", "note": "two chapters"}, {"habit": "read", "day": "2026-10-32"}, {"habit": "Read!", "day": "2026-10-22"}, {"habit": "read"}, ["read", "2026-10-22"],]for raw in samples: try: print("ok: ", parse_checkin(raw)) except InvalidRecord as e: print("skip:", e, "| caused by:", repr(e.__cause__))print(parse_habit({"name": "stretch", "per_week": 3}))try: parse_habit({"name": "stretch", "per_week": 9})except TrackerError as e: print("skip:", e)
Output
Press Run (⌘ Enter) to see what happens.
Check: one sample parses, four are skipped with a reason, and only the bad date has a cause attached.
Stage 3: files on disk
Now the data needs to survive between runs. This stage adds four functions, built on Files and JSON and Context Managers.
save_habits writes the habit list with a safe pattern: write the whole file to habits.tmp, then call Path.replace to swap it into place. On the same disk, a replace is atomic, so a crash or a full disk halfway through leaves the old file intact rather than a half-written one. load_habits reads it back with a list comprehension and turns broken JSON into a TrackerError, so the user sees "habits.json is not valid JSON" instead of a traceback about line and column numbers.
The log uses JSON Lines: one JSON object per line. Appending is cheap, and one damaged line does not ruin the rest of the file. read_checkins is a generator from Iterators and Generators. It opens the file in a with block, reads one line at a time and yields one CheckIn per good line. A bad line is recorded in a problems list, with its line number, and the generator moves on. The log could hold ten years of check-ins and memory use would stay flat. Every file call passes encoding="utf-8", so notes do not depend on the computer's default encoding.
import jsonimport reimport tempfilefrom collections.abc import Iteratorfrom dataclasses import dataclassfrom datetime import datefrom pathlib import PathNAME = re.compile(r"[a-z][a-z0-9-]{0,29}")@dataclass(frozen=True, slots=True)class Habit: name: str per_week: int@dataclass(frozen=True, slots=True)class CheckIn: habit: str day: date note: str = ""class TrackerError(Exception): """Base class for every error this app raises on purpose."""class InvalidRecord(TrackerError): """A record from a file or the command line is not valid."""def check_name(name: str) -> str: if not NAME.fullmatch(name): raise InvalidRecord(f"bad habit name {name!r}: use a-z, 0-9 and -") return namedef parse_habit(raw: object) -> Habit: match raw: case {"name": str(name), "per_week": int(n)} if 1 <= n <= 7: return Habit(check_name(name), n) case {"name": str(), "per_week": int()}: raise InvalidRecord("per_week must be between 1 and 7") case _: raise InvalidRecord(f"not a habit: {raw!r}")def parse_checkin(raw: object) -> CheckIn: match raw: case {"habit": str(habit), "day": str(day), **rest}: try: parsed = date.fromisoformat(day) except ValueError as e: raise InvalidRecord(f"bad day {day!r}") from e note = rest.get("note", "") if not isinstance(note, str): raise InvalidRecord("note must be text") return CheckIn(check_name(habit), parsed, note) case _: raise InvalidRecord(f"not a check-in: {raw!r}")# --- storage: new in this stage ---def load_habits(path: Path) -> dict[str, Habit]: if not path.exists(): return {} try: raw = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError as e: raise TrackerError(f"{path.name} is not valid JSON") from e habits = [parse_habit(item) for item in raw] return {h.name: h for h in habits}def save_habits(path: Path, habits: dict[str, Habit]) -> None: data = [{"name": h.name, "per_week": h.per_week} for h in habits.values()] tmp = path.with_suffix(".tmp") tmp.write_text(json.dumps(data, indent=2), encoding="utf-8") tmp.replace(path) # atomic: readers see the old file or the new onedef append_checkin(path: Path, checkin: CheckIn) -> None: record = {"habit": checkin.habit, "day": checkin.day.isoformat()} if checkin.note: record["note"] = checkin.note with path.open("a", encoding="utf-8") as f: f.write(json.dumps(record) + "\n")def read_checkins(path: Path, problems: list[str]) -> Iterator[CheckIn]: """Yield valid check-ins one line at a time. Bad lines go into problems.""" if not path.exists(): return with path.open(encoding="utf-8") as f: for number, line in enumerate(f, start=1): if not line.strip(): continue try: yield parse_checkin(json.loads(line)) except (json.JSONDecodeError, InvalidRecord) as e: problems.append(f"line {number}: {e}")with tempfile.TemporaryDirectory() as folder: data = Path(folder) habits_file = data / "habits.json" log_file = data / "checkins.jsonl" save_habits(habits_file, {"read": Habit("read", 5), "run": Habit("run", 3)}) append_checkin(log_file, CheckIn("read", date(2026, 10, 21))) append_checkin(log_file, CheckIn("run", date(2026, 10, 22), note="5 km")) with log_file.open("a", encoding="utf-8") as f: f.write('{"habit": "read", "day": "2026-10-23"\n') # cut off mid-write append_checkin(log_file, CheckIn("read", date(2026, 10, 22))) print(habits_file.read_text(encoding="utf-8")) print(log_file.read_text(encoding="utf-8")) print("Habits:", sorted(load_habits(habits_file))) problems: list[str] = [] checkins = read_checkins(log_file, problems) print("Generator made, nothing read yet:", problems) for c in checkins: print(" ", c.habit, c.day, c.note) print("Problems:", problems)
Output
Press Run (⌘ Enter) to see what happens.
The demo writes a line that was cut off mid-write, which is exactly what you would find after a crash. Notice the line Generator made, nothing read yet: []. Calling read_checkins runs none of its body. The file is opened only when the for loop asks for the first item, and the problem is recorded only when the loop reaches line 3.
Check: three check-ins print, the problem list names line 3, and the habits file is readable, indented JSON.
Predict the outputPython
What does this print?
problems = []
def read(lines):
for n, line in enumerate(lines, start=1):
if line.isdigit():
yield int(line)
else:
problems.append(n)
gen = read(["1", "x", "3", "y"])
print(len(problems))
print(next(gen), len(problems))
print(sum(gen), problems)
Need a nudge? Hints walk you through it.
Stage 4: the weekly report
The report answers two questions per habit: how many days have you done it this week, and what is your current streak? This is the logic layer, and it does not touch files. build_report accepts any Iterable[CheckIn], so you can pass it a list in a test or the generator from stage 3 in the app. The storage code is left out of this block for that reason.
Three choices make it correct:
Days, not records. Check-ins are grouped into a set of days per habit, so checking in twice on Friday counts once. A dict comprehension starts with an empty set per known habit, so unknown habits are ignored.
A streak survives until the day is over.streak starts from yesterday when today is missing.
"Today" is a parameter. The function never calls date.today(). That one decision makes every test deterministic, as Testing Code That Touches the Outside World showed. The weekday maths comes from Dates, Times and Time Zones: today.weekday() is 0 on Monday, so subtracting it gives the start of the week.
The weekly count uses a generator expression from Comprehensions, sum(1 for d in days if d >= week_start), which counts without building a list. The rows are sorted with a key function from Higher-Order Functions: habits that are behind come first, then longer streaks, then by name. render lines up the columns with the format spec mini-language from Strings Deep Dive.
from collections.abc import Iterablefrom dataclasses import dataclassfrom datetime import date, timedelta@dataclass(frozen=True, slots=True)class Habit: name: str per_week: int@dataclass(frozen=True, slots=True)class CheckIn: habit: str day: date note: str = ""# --- the report: new in this stage ---@dataclass(frozen=True, slots=True)class Row: habit: str done_this_week: int per_week: int streak: int @property def on_track(self) -> bool: return self.done_this_week >= self.per_weekdef streak(days: set[date], today: date) -> int: """Consecutive days up to today. A missing today does not break it yet.""" day = today if today in days else today - timedelta(days=1) count = 0 while day in days: count += 1 day -= timedelta(days=1) return countdef build_report(habits: dict[str, Habit], checkins: Iterable[CheckIn], today: date) -> list[Row]: days_by_habit: dict[str, set[date]] = {name: set() for name in habits} for c in checkins: if c.habit in days_by_habit and c.day <= today: days_by_habit[c.habit].add(c.day) week_start = today - timedelta(days=today.weekday()) # Monday rows = [ Row( habit=name, done_this_week=sum(1 for d in days if d >= week_start), per_week=habits[name].per_week, streak=streak(days, today), ) for name, days in days_by_habit.items() ] return sorted(rows, key=lambda r: (r.on_track, -r.streak, r.habit))def render(rows: list[Row]) -> str: lines = [f"{'habit':<10} {'week':<5} {'streak':>6}"] for r in rows: mark = "ok" if r.on_track else "behind" lines.append(f"{r.habit:<10} {r.done_this_week:>2}/{r.per_week:<2} {r.streak:>6} {mark}") return "\n".join(lines)today = date(2026, 10, 23) # a Fridayhabits = {"read": Habit("read", 5), "run": Habit("run", 3), "stretch": Habit("stretch", 2)}checkins = [CheckIn("read", today - timedelta(days=n)) for n in range(6)]checkins += [CheckIn("run", date(2026, 10, d)) for d in (20, 22)]checkins += [CheckIn("stretch", date(2026, 10, 22)), CheckIn("stretch", date(2026, 10, 22))]checkins.append(CheckIn("swim", today)) # no such habit: ignoredprint(render(build_report(habits, checkins, today)))
Output
Press Run (⌘ Enter) to see what happens.
Check:read has 5 of 5 and a six-day streak, stretch shows 1 of 2 even though it has two check-ins on the same day, and swim does not appear.
Quick check
It is Friday. You read on Tuesday, Wednesday and Thursday, but not yet today. What does streak(days, today) return, and why?
Need a nudge? A hint rules out a wrong answer.
Stage 5: the command line
Now wire it together. The interface follows Scripting and Automation: argparse with three subcommands, add, done and report. Look at --day: its type is date.fromisoformat, so argparse converts the string for you and prints a usage error if it is not a valid date.
main has two design choices you will see in most well-built tools:
It takes argv, data_dir and today as parameters. A tiny __main__.py passes the real values. Tests pass their own.
It returns an exit code instead of calling sys.exit. Success is 0 and an expected failure is 1, with the message on standard error. argparse itself uses 2 for bad arguments. The demo uses contextlib.redirect_stderr so errors print in order.
Every TrackerError from any layer, a bad name, a broken file or an unknown habit, ends at one except with one message format.
import argparseimport contextlibimport jsonimport reimport shleximport sysimport tempfilefrom collections.abc import Iterable, Iteratorfrom dataclasses import dataclassfrom datetime import date, timedeltafrom pathlib import PathNAME = re.compile(r"[a-z][a-z0-9-]{0,29}")@dataclass(frozen=True, slots=True)class Habit: name: str per_week: int@dataclass(frozen=True, slots=True)class CheckIn: habit: str day: date note: str = ""class TrackerError(Exception): """Base class for every error this app raises on purpose."""class InvalidRecord(TrackerError): """A record from a file or the command line is not valid."""def check_name(name: str) -> str: if not NAME.fullmatch(name): raise InvalidRecord(f"bad habit name {name!r}: use a-z, 0-9 and -") return namedef parse_habit(raw: object) -> Habit: match raw: case {"name": str(name), "per_week": int(n)} if 1 <= n <= 7: return Habit(check_name(name), n) case {"name": str(), "per_week": int()}: raise InvalidRecord("per_week must be between 1 and 7") case _: raise InvalidRecord(f"not a habit: {raw!r}")def parse_checkin(raw: object) -> CheckIn: match raw: case {"habit": str(habit), "day": str(day), **rest}: try: parsed = date.fromisoformat(day) except ValueError as e: raise InvalidRecord(f"bad day {day!r}") from e note = rest.get("note", "") if not isinstance(note, str): raise InvalidRecord("note must be text") return CheckIn(check_name(habit), parsed, note) case _: raise InvalidRecord(f"not a check-in: {raw!r}")# --- storage: new in this stage ---def load_habits(path: Path) -> dict[str, Habit]: if not path.exists(): return {} try: raw = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError as e: raise TrackerError(f"{path.name} is not valid JSON") from e habits = [parse_habit(item) for item in raw] return {h.name: h for h in habits}def save_habits(path: Path, habits: dict[str, Habit]) -> None: data = [{"name": h.name, "per_week": h.per_week} for h in habits.values()] tmp = path.with_suffix(".tmp") tmp.write_text(json.dumps(data, indent=2), encoding="utf-8") tmp.replace(path) # atomic: readers see the old file or the new onedef append_checkin(path: Path, checkin: CheckIn) -> None: record = {"habit": checkin.habit, "day": checkin.day.isoformat()} if checkin.note: record["note"] = checkin.note with path.open("a", encoding="utf-8") as f: f.write(json.dumps(record) + "\n")def read_checkins(path: Path, problems: list[str]) -> Iterator[CheckIn]: """Yield valid check-ins one line at a time. Bad lines go into problems.""" if not path.exists(): return with path.open(encoding="utf-8") as f: for number, line in enumerate(f, start=1): if not line.strip(): continue try: yield parse_checkin(json.loads(line)) except (json.JSONDecodeError, InvalidRecord) as e: problems.append(f"line {number}: {e}")# --- the report: new in this stage ---@dataclass(frozen=True, slots=True)class Row: habit: str done_this_week: int per_week: int streak: int @property def on_track(self) -> bool: return self.done_this_week >= self.per_weekdef streak(days: set[date], today: date) -> int: """Consecutive days up to today. A missing today does not break it yet.""" day = today if today in days else today - timedelta(days=1) count = 0 while day in days: count += 1 day -= timedelta(days=1) return countdef build_report(habits: dict[str, Habit], checkins: Iterable[CheckIn], today: date) -> list[Row]: days_by_habit: dict[str, set[date]] = {name: set() for name in habits} for c in checkins: if c.habit in days_by_habit and c.day <= today: days_by_habit[c.habit].add(c.day) week_start = today - timedelta(days=today.weekday()) # Monday rows = [ Row( habit=name, done_this_week=sum(1 for d in days if d >= week_start), per_week=habits[name].per_week, streak=streak(days, today), ) for name, days in days_by_habit.items() ] return sorted(rows, key=lambda r: (r.on_track, -r.streak, r.habit))def render(rows: list[Row]) -> str: lines = [f"{'habit':<10} {'week':<5} {'streak':>6}"] for r in rows: mark = "ok" if r.on_track else "behind" lines.append(f"{r.habit:<10} {r.done_this_week:>2}/{r.per_week:<2} {r.streak:>6} {mark}") return "\n".join(lines)# --- the command line: new in this stage ---def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(prog="habits", description="Track daily habits.") sub = parser.add_subparsers(dest="command", required=True) add = sub.add_parser("add", help="start tracking a habit") add.add_argument("name") add.add_argument("--per-week", type=int, default=7) done = sub.add_parser("done", help="check in a habit") done.add_argument("name") done.add_argument("--day", type=date.fromisoformat, help="YYYY-MM-DD, default today") done.add_argument("--note", default="") sub.add_parser("report", help="show this week and streaks") return parserdef main(argv: list[str] | None = None, *, data_dir: Path, today: date) -> int: args = build_parser().parse_args(argv) habits_file = data_dir / "habits.json" log_file = data_dir / "checkins.jsonl" try: habits = load_habits(habits_file) match args.command: case "add": habit = parse_habit({"name": args.name, "per_week": args.per_week}) habits[habit.name] = habit save_habits(habits_file, habits) print(f"Tracking {habit.name}, {habit.per_week} days a week.") case "done": if args.name not in habits: raise TrackerError(f"unknown habit {args.name!r}. Try: habits add {args.name}") day = args.day or today if day > today: raise TrackerError("you cannot check in a day in the future") append_checkin(log_file, CheckIn(args.name, day, args.note)) print(f"Checked in {args.name} for {day}.") case "report": problems: list[str] = [] rows = build_report(habits, read_checkins(log_file, problems), today) print(render(rows)) for p in problems: print(f"warning: skipped {p}", file=sys.stderr) except TrackerError as e: print(f"error: {e}", file=sys.stderr) return 1 return 0with tempfile.TemporaryDirectory() as folder: env = {"data_dir": Path(folder), "today": date(2026, 10, 23)} commands = [ ["add", "read", "--per-week", "5"], ["add", "run", "--per-week", "3"], ["add", "Run Fast"], ["add", "swim", "--per-week", "9"], ["done", "read", "--day", "2026-10-21"], ["done", "read", "--day", "2026-10-22"], ["done", "read", "--note", "finished the book"], ["done", "run"], ["done", "swim"], ["done", "run", "--day", "2026-10-30"], ["report"], ] with contextlib.redirect_stderr(sys.stdout): # show errors in order for argv in commands: print("$", shlex.join(["habits", *argv])) code = main(argv, **env) if code: print("exit code", code)
Output
Press Run (⌘ Enter) to see what happens.
Check: the four bad commands each print one error: line and exit with code 1, the good ones print a confirmation, and the report shows read with three days and a three-day streak.
Match the pairs0/5 matched
Match each part of the tracker to the lesson that taught the idea behind it.
Choose an item, then its match on the other side.
Stage 6: tests with plain asserts
Pure functions, injected dates and a data folder you pass in make the tests short. Each test below is a plain function whose name starts with test_ and that uses bare assert. That is exactly the style Testing with pytest uses: pytest finds these functions, runs them and rewrites assert to show the values when one fails. Here, a small loop at the bottom does that job.
The tests pin down the streak rules, the "count a day once" rule, error causes, bad log lines, a save and load round trip, a corrupt file and the exit code. Tests that touch files each create their own temporary folder with tempfile.TemporaryDirectory, so they never see each other's data or your real files. With pytest you would use the tmp_path fixture for the same job. Expected exceptions use try, except and else: assert False, which is what pytest.raises does for you.
import argparseimport contextlibimport ioimport jsonimport reimport sysimport tempfilefrom collections.abc import Iterable, Iteratorfrom dataclasses import dataclassfrom datetime import date, timedeltafrom pathlib import PathNAME = re.compile(r"[a-z][a-z0-9-]{0,29}")@dataclass(frozen=True, slots=True)class Habit: name: str per_week: int@dataclass(frozen=True, slots=True)class CheckIn: habit: str day: date note: str = ""class TrackerError(Exception): """Base class for every error this app raises on purpose."""class InvalidRecord(TrackerError): """A record from a file or the command line is not valid."""def check_name(name: str) -> str: if not NAME.fullmatch(name): raise InvalidRecord(f"bad habit name {name!r}: use a-z, 0-9 and -") return namedef parse_habit(raw: object) -> Habit: match raw: case {"name": str(name), "per_week": int(n)} if 1 <= n <= 7: return Habit(check_name(name), n) case {"name": str(), "per_week": int()}: raise InvalidRecord("per_week must be between 1 and 7") case _: raise InvalidRecord(f"not a habit: {raw!r}")def parse_checkin(raw: object) -> CheckIn: match raw: case {"habit": str(habit), "day": str(day), **rest}: try: parsed = date.fromisoformat(day) except ValueError as e: raise InvalidRecord(f"bad day {day!r}") from e note = rest.get("note", "") if not isinstance(note, str): raise InvalidRecord("note must be text") return CheckIn(check_name(habit), parsed, note) case _: raise InvalidRecord(f"not a check-in: {raw!r}")# --- storage: new in this stage ---def load_habits(path: Path) -> dict[str, Habit]: if not path.exists(): return {} try: raw = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError as e: raise TrackerError(f"{path.name} is not valid JSON") from e habits = [parse_habit(item) for item in raw] return {h.name: h for h in habits}def save_habits(path: Path, habits: dict[str, Habit]) -> None: data = [{"name": h.name, "per_week": h.per_week} for h in habits.values()] tmp = path.with_suffix(".tmp") tmp.write_text(json.dumps(data, indent=2), encoding="utf-8") tmp.replace(path) # atomic: readers see the old file or the new onedef append_checkin(path: Path, checkin: CheckIn) -> None: record = {"habit": checkin.habit, "day": checkin.day.isoformat()} if checkin.note: record["note"] = checkin.note with path.open("a", encoding="utf-8") as f: f.write(json.dumps(record) + "\n")def read_checkins(path: Path, problems: list[str]) -> Iterator[CheckIn]: """Yield valid check-ins one line at a time. Bad lines go into problems.""" if not path.exists(): return with path.open(encoding="utf-8") as f: for number, line in enumerate(f, start=1): if not line.strip(): continue try: yield parse_checkin(json.loads(line)) except (json.JSONDecodeError, InvalidRecord) as e: problems.append(f"line {number}: {e}")# --- the report: new in this stage ---@dataclass(frozen=True, slots=True)class Row: habit: str done_this_week: int per_week: int streak: int @property def on_track(self) -> bool: return self.done_this_week >= self.per_weekdef streak(days: set[date], today: date) -> int: """Consecutive days up to today. A missing today does not break it yet.""" day = today if today in days else today - timedelta(days=1) count = 0 while day in days: count += 1 day -= timedelta(days=1) return countdef build_report(habits: dict[str, Habit], checkins: Iterable[CheckIn], today: date) -> list[Row]: days_by_habit: dict[str, set[date]] = {name: set() for name in habits} for c in checkins: if c.habit in days_by_habit and c.day <= today: days_by_habit[c.habit].add(c.day) week_start = today - timedelta(days=today.weekday()) # Monday rows = [ Row( habit=name, done_this_week=sum(1 for d in days if d >= week_start), per_week=habits[name].per_week, streak=streak(days, today), ) for name, days in days_by_habit.items() ] return sorted(rows, key=lambda r: (r.on_track, -r.streak, r.habit))def render(rows: list[Row]) -> str: lines = [f"{'habit':<10} {'week':<5} {'streak':>6}"] for r in rows: mark = "ok" if r.on_track else "behind" lines.append(f"{r.habit:<10} {r.done_this_week:>2}/{r.per_week:<2} {r.streak:>6} {mark}") return "\n".join(lines)# --- the command line: new in this stage ---def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(prog="habits", description="Track daily habits.") sub = parser.add_subparsers(dest="command", required=True) add = sub.add_parser("add", help="start tracking a habit") add.add_argument("name") add.add_argument("--per-week", type=int, default=7) done = sub.add_parser("done", help="check in a habit") done.add_argument("name") done.add_argument("--day", type=date.fromisoformat, help="YYYY-MM-DD, default today") done.add_argument("--note", default="") sub.add_parser("report", help="show this week and streaks") return parserdef main(argv: list[str] | None = None, *, data_dir: Path, today: date) -> int: args = build_parser().parse_args(argv) habits_file = data_dir / "habits.json" log_file = data_dir / "checkins.jsonl" try: habits = load_habits(habits_file) match args.command: case "add": habit = parse_habit({"name": args.name, "per_week": args.per_week}) habits[habit.name] = habit save_habits(habits_file, habits) print(f"Tracking {habit.name}, {habit.per_week} days a week.") case "done": if args.name not in habits: raise TrackerError(f"unknown habit {args.name!r}. Try: habits add {args.name}") day = args.day or today if day > today: raise TrackerError("you cannot check in a day in the future") append_checkin(log_file, CheckIn(args.name, day, args.note)) print(f"Checked in {args.name} for {day}.") case "report": problems: list[str] = [] rows = build_report(habits, read_checkins(log_file, problems), today) print(render(rows)) for p in problems: print(f"warning: skipped {p}", file=sys.stderr) except TrackerError as e: print(f"error: {e}", file=sys.stderr) return 1 return 0# --- tests: new in this stage ---FRIDAY = date(2026, 10, 23)def test_streak_survives_until_today_is_over(): days = {FRIDAY - timedelta(days=n) for n in (1, 2, 3)} assert streak(days, FRIDAY) == 3 assert streak(days | {FRIDAY}, FRIDAY) == 4def test_streak_stops_at_a_gap(): days = {FRIDAY, FRIDAY - timedelta(days=2)} assert streak(days, FRIDAY) == 1def test_report_counts_a_day_once(): habits = {"read": Habit("read", 2)} twice = [CheckIn("read", FRIDAY), CheckIn("read", FRIDAY, note="again")] [row] = build_report(habits, twice, FRIDAY) assert row.done_this_week == 1 assert not row.on_trackdef test_bad_day_keeps_the_cause(): try: parse_checkin({"habit": "read", "day": "2026-02-30"}) except InvalidRecord as e: assert isinstance(e.__cause__, ValueError) else: assert False, "expected InvalidRecord"def test_reader_skips_bad_lines_and_says_where(): with tempfile.TemporaryDirectory() as folder: log = Path(folder) / "checkins.jsonl" log.write_text( '{"habit": "read", "day": "2026-10-22"}\n' "not json\n" '{"habit": "read", "day": "yesterday"}\n', encoding="utf-8", ) problems: list[str] = [] found = list(read_checkins(log, problems)) assert [c.day for c in found] == [date(2026, 10, 22)] assert [p.split(":")[0] for p in problems] == ["line 2", "line 3"]def test_habits_round_trip_through_the_file(): with tempfile.TemporaryDirectory() as folder: path = Path(folder) / "habits.json" habits = {"read": Habit("read", 5), "run": Habit("run", 3)} save_habits(path, habits) assert load_habits(path) == habits assert not path.with_suffix(".tmp").exists()def test_corrupt_habits_file_is_a_tracker_error(): with tempfile.TemporaryDirectory() as folder: path = Path(folder) / "habits.json" path.write_text("[{", encoding="utf-8") try: load_habits(path) except TrackerError as e: assert "not valid JSON" in str(e) else: assert False, "expected TrackerError"def test_cli_rejects_unknown_habit_with_exit_code_1(): with tempfile.TemporaryDirectory() as folder: err = io.StringIO() with contextlib.redirect_stderr(err): code = main(["done", "swim"], data_dir=Path(folder), today=FRIDAY) assert code == 1 assert "unknown habit 'swim'" in err.getvalue() assert not (Path(folder) / "checkins.jsonl").exists()# A tiny runner. pytest finds the same test_ functions without it.tests = [fn for name, fn in globals().items() if name.startswith("test_")]failed = 0for test in tests: try: test() print("PASS", test.__name__) except AssertionError as e: failed += 1 print("FAIL", test.__name__, e)print(f"{len(tests) - failed} passed, {failed} failed")
Output
Press Run (⌘ Enter) to see what happens.
Check: all eight tests pass. Then break streak on purpose: make it always start from today, and watch exactly one test fail. A test you have never seen fail is a test you cannot fully trust.
Put it in order4 steps
Put the steps of save_habits in the order that keeps habits.json safe if the program crashes partway.
Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
On your own machine
To use the tracker for real, split the code into a package the way Project Structure describes: models.py, storage.py, report.py and cli.py under src/habits/, with the tests in tests/test_habits.py. The only new file is the entry point, which is the one place that reads the real clock and picks a real folder:
With main called with no argv, argparse reads sys.argv as usual. In the tests file, delete the runner loop at the bottom and import from your package instead. Then, from the project folder, with your virtual environment active, install the project in editable mode with pip install -e . and install pytest, as Project Structure and Testing with pytest showed. Now run:
You should see Tracking read, 5 days a week., then Checked in read for today's date, then a one-row table, and pytest should finish with 8 passed.
Make it yours
The core is done. These would turn it into a portfolio piece:
Undo and edit. Add habits undo to remove the last check-in. The log is append-only, so decide between rewriting it atomically or appending a "deleted" record, and write down why.
A --json report. Print the rows as JSON with dataclasses.asdict, so other tools can use the output. Add a test that parses what you print.
Monthly history. Show a small calendar grid per habit for the last four weeks, built from the same set of days.
Weekly targets that change. Store the date a target changed, so last month's report still uses last month's target.
Package and publish it. Add a pyproject.toml with a habits script entry point, lint and type-check it in CI, and release it, following Packaging and Publishing a Library.
When you write it up, the Interview Prep lesson Writing Project Case Studies shows how to turn a project like this into a short case study.
Build it for real in the Project Lab
Browser builds that train the same habits of small functions and tested logic:
Split the pizza bill has a pure money function that rounds to cents, with checks that catch the off-by-a-penny bugs.
A dataclass created with frozen=True, whose fields cannot be reassigned and which gets a __hash__ so it can live in sets.
JSON Lines
A file format with one JSON value per line, easy to append to and readable one line at a time.
atomic write
Writing to a temporary file and then replacing the real one, so readers see either the old file or the new one, never half of each.
exception chaining
Raising a new exception with raise ... from e, which keeps the original as __cause__.
exit code
The number a program returns to the shell: 0 for success and a non-zero value for each kind of failure.
injected clock
Passing the current date or time into a function instead of reading it inside, so tests can choose the date.
That is a tool you could use every day. The wrap-up next pulls the whole track together around a bigger job, from an empty folder to a tested, secure report that runs every night.