N
NexusDigitalLabs
← Back to Academy

Phase 1 — Foundations · Lesson 5 · 20 XP

Standard-library CLI: argparse, json, csv (todo app capstone)

argparse builds real command-line interfaces: positional arguments (required, order-based), optional flags (--title, -t), and subcommands (todo add, todo list, todo done) via add_subparsers. This is the difference between a script and a tool someone else can run without reading the source.

import argparse

parser = argparse.ArgumentParser(prog="todo")
sub = parser.add_subparsers(dest="command", required=True)

add_p = sub.add_parser("add")
add_p.add_argument("title")

args = parser.parse_args()
if args.command == "add":
    print(f"adding: {args.title}")

json.dumps/json.loads persist structured data as text — the natural fit for a list of dataclass-shaped records. The csv module (DictReader/DictWriter) does the same for tabular data with named columns, which is what you already used in Lesson 3.

This lesson is a capstone: it doesn't teach much new syntax, it asks you to combine dataclasses, pathlib, exceptions, logging, and argparse from Lessons 1-4 into one real command-line tool.

Exercise

Build a complete todo CLI with add/list/done subcommands, persisting to a JSON file with pathlib, using a Todo dataclass, and logging (not printing) errors like a missing file or an invalid id.

Check yourself

1. What's the difference between a positional and an optional (--flag) argparse argument?

2. Why does storing todos as JSON make more sense here than a raw line-per-todo text file?

← Previous lesson

Python core III: exceptions, logging, generators, context managers

Answer the check-yourself questions to unlock this