taskbox: a Packaged CLI Tool
A real, multi-file, pip-installable command-line task manager — not a single-file script. taskbox has four subcommands (add, list, done, delete), persists tasks to a JSON file, uses real logging instead of print() for its diagnostic output, and ships with a correct pyproject.toml so it can be installed with pip install -e . and run as a plain taskbox command from anywhere on your machine.
project/
├── starter/ <- you work here
│ └── taskbox/
│ ├── __init__.py
│ ├── core.py (TODOs 1-14 -- the task logic)
│ └── cli.py (TODOs 15-26 -- the argparse wiring)
├── solution/ <- complete, working reference
│ ├── taskbox/
│ │ ├── __init__.py
│ │ ├── core.py
│ │ └── cli.py
│ ├── pyproject.toml
│ ├── requirements.txt
│ └── README.md
What you're building
taskbox add "<title>" [--priority low|normal|high]— add a task.taskbox list [--all] [--priority ...]— list tasks (pending only by default;--allincludes completed ones).taskbox done <id>— mark a task complete.taskbox delete <id>— delete a task.- A top-level
--file <path>flag on every subcommand, pointing at which JSON file to read/write (defaults to~/.taskbox/tasks.json). - A top-level
-v/--verboseflag that raises the tool's own log level from INFO to DEBUG — without flooding the terminal with debug noise from any library the tool might import.
core.py holds the actual task logic — loading/saving the JSON file, adding/listing/completing/deleting tasks. It never imports argparse, never touches sys.argv, and never calls print(). cli.py holds the argparse parser and is the only place that talks to the terminal. This split means core.py could be reused by a future web API or test suite with zero changes, because it doesn't know a terminal exists.
Build it: core.py first
1 Load and save tasks (TODOs 1-8)
load_tasks reads the JSON file (returning [] if it doesn't exist yet — that's a normal first run, not an error) and raises TaskboxError with a clear message if the file is unreadable or corrupted. save_tasks writes the list back, creating the parent folder if needed.
def load_tasks(tasks_file: Path) -> list[dict]:
if not tasks_file.exists():
logger.debug("Tasks file %s does not exist yet -- starting empty", tasks_file)
return []
try:
raw = tasks_file.read_text(encoding="utf-8")
except OSError as exc:
raise TaskboxError(f"Could not read tasks file {tasks_file}: {exc}") from exc
if not raw.strip():
return []
try:
data = json.loads(raw)
except json.JSONDecodeError as exc:
raise TaskboxError(
f"Tasks file {tasks_file} is not valid JSON (corrupted?): {exc}"
) from exc
if not isinstance(data, list):
raise TaskboxError(f"Tasks file {tasks_file} does not contain a JSON list.")
return data
Thought process: a file-loading function has three separate failure modes that all need distinct handling — missing file (normal, return empty), unreadable file (OS-level problem, wrap it), and corrupted contents (bad JSON, wrap it separately). Catching a bare Exception around the whole thing would hide which of the three actually happened, making the error message useless for debugging.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
Write a Python function load_tasks(tasks_file: Path) -> list[dict] that reads a JSON list of task dicts from a file. Requirements: (1) if the file doesn't exist, return an empty list -- this is the normal first-run case, not an error; (2) if the file can't be read (permissions, etc.), raise a custom TaskboxError with a clear message, chained from the original OSError; (3) if the file's contents aren't valid JSON, raise TaskboxError with a "corrupted?" message, chained from the original JSONDecodeError; (4) if the parsed JSON isn't a list, also raise TaskboxError. Use the logging module (not print) to log a debug message when the file doesn't exist yet.
2 Add, list, complete, delete (TODOs 9-14)
add_task validates the title and priority, computes the next id, and appends a new task dict. list_tasks filters by completion state and priority. complete_task and delete_task both reuse a small _find_task helper that raises TaskboxError if the id doesn't exist — one place to get "no task with that id" right, instead of repeating the check four times.
def add_task(tasks_file: Path, title: str, priority: str = "normal") -> dict:
title = title.strip()
if not title:
raise TaskboxError("Task title cannot be empty.")
valid_priorities = {"low", "normal", "high"}
if priority not in valid_priorities:
raise TaskboxError(
f"Invalid priority {priority!r}. Choose from: {', '.join(sorted(valid_priorities))}."
)
tasks = load_tasks(tasks_file)
next_id = (max((t["id"] for t in tasks), default=0)) + 1
task = {
"id": next_id,
"title": title,
"priority": priority,
"done": False,
"created_at": _now_iso(),
"completed_at": None,
}
tasks.append(task)
save_tasks(tasks_file, tasks)
logger.info("Added task #%d: %s", next_id, title)
return task
Build it: cli.py
3 Build the argparse parser with subcommands (TODOs 15-20)
One top-level parser owns the shared --file and -v/--verbose flags. add_subparsers(dest="command", required=True) creates the add/list/done/delete subcommands, each with its own arguments — title is positional (required) on add, while --priority is optional with a default.
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="taskbox",
description="A small command-line task manager backed by a JSON file.",
)
parser.add_argument("--file", type=Path, default=DEFAULT_TASKS_FILE,
help=f"path to the tasks JSON file (default: {DEFAULT_TASKS_FILE})")
parser.add_argument("-v", "--verbose", action="store_true",
help="show debug-level logging (task file paths, filtering details, etc.)")
subparsers = parser.add_subparsers(dest="command", required=True)
add_parser = subparsers.add_parser("add", help="add a new task")
add_parser.add_argument("title", help="the task's title (required, positional)")
add_parser.add_argument("--priority", choices=["low", "normal", "high"],
default="normal", help="task priority (default: normal)")
list_parser = subparsers.add_parser("list", help="list tasks")
list_parser.add_argument("--all", action="store_true",
help="include already-completed tasks (default: only show pending)")
list_parser.add_argument("--priority", choices=["low", "normal", "high"],
default=None, help="only show tasks with this priority")
done_parser = subparsers.add_parser("done", help="mark a task complete")
done_parser.add_argument("id", type=int, help="the task's numeric id")
delete_parser = subparsers.add_parser("delete", help="delete a task")
delete_parser.add_argument("id", type=int, help="the task's numeric id")
return parser
Thought process: the difference between a positional argument (title) and an optional flag (--priority) is a judgment call about what's always required for a command to make sense — you can't "add" a task with no title, but priority has a sensible default. Getting this backwards (making title optional, or priority positional) is a common AI mistake worth checking for explicitly.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
Write an argparse.ArgumentParser for a CLI tool called "taskbox" with a top-level --file (Path, default ~/.taskbox/tasks.json) and -v/--verbose (store_true) flag, plus four subcommands using add_subparsers(dest="command", required=True): "add" (required positional "title" string, optional --priority with choices low/normal/high defaulting to "normal"), "list" (--all store_true flag, optional --priority filter defaulting to None), "done" (required positional "id" as int), and "delete" (required positional "id" as int). Return the built parser from a build_parser() function -- don't call parse_args() inside it.
4 Configure logging correctly (TODO 21)
This is the part that's easy to get subtly wrong: logging.basicConfig() configures the root logger, which every imported library's logger flows into by default. If --verbose called basicConfig(level=logging.DEBUG), it would flood the terminal with debug output from every dependency this tool imports too — not just taskbox's own messages. Attaching a handler to the "taskbox" logger specifically, and setting propagate = False, keeps --verbose scoped to this tool.
logger = logging.getLogger("taskbox")
def configure_logging(verbose: bool) -> None:
level = logging.DEBUG if verbose else logging.INFO
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
logger.addHandler(handler)
logger.setLevel(level)
logger.propagate = False
Real output — without -v, only INFO lines show:
$ taskbox --file /tmp/demo_tasks.json add "Ship chapter 31"
INFO: Added task #1: Ship chapter 31
Added task #1: Ship chapter 31
With -v, the DEBUG lines from core.py's logger.debug(...) calls appear too — nothing had to be deleted or commented out to quiet them down normally, one flag controls it:
$ taskbox --file /tmp/demo_tasks.json -v add "Debug this"
DEBUG: Loading tasks from /tmp/demo_tasks.json
DEBUG: Saving 3 task(s) to /tmp/demo_tasks.json
INFO: Added task #3: Debug this
Added task #3: Debug this
5 Wire subcommands to core.py, handle errors (TODOs 22-26)
main() dispatches on args.command, calling into the matching core.py function and printing the result. Everything is wrapped in try/except TaskboxError — a caught error logs a clear message and returns exit code 1, instead of a raw Python traceback reaching the user.
$ taskbox --file /tmp/demo_tasks.json done 999
ERROR: No task with id 999.
$ echo $?
1
A missing required argument never even reaches this code — argparse catches it before main()'s body runs:
$ taskbox add
usage: taskbox add [-h] [--priority {low,normal,high}] title
taskbox add: error: the following arguments are required: title
$ echo $?
2
Install it for real
This is the part that makes it a genuinely "packaged" CLI tool, not just a script — installing it with pip so taskbox becomes a normal command on your PATH, runnable from any directory.
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[project]
name = "taskbox"
version = "1.0.0"
description = "A small command-line task manager backed by a JSON file."
readme = "README.md"
requires-python = ">=3.9"
license = { text = "MIT" }
authors = [
{ name = "Your Name" }
]
[project.scripts]
taskbox = "taskbox.cli:main"
[tool.setuptools]
packages = ["taskbox"]
[project.scripts] is what actually creates the taskbox command: it tells pip "install an executable named taskbox that calls main() in taskbox/cli.py." This is the same mechanism (called console_scripts under the hood) that gives you the pip, black, and pytest commands after installing those packages.
cd chapters/chapter-31-professional-python/project/solution
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -e .
-e (editable) installs the package in a way that still reads from this source folder — changes to taskbox/*.py take effect immediately, no reinstall needed. This is real output from actually running that install:
$ pip install -e .
Obtaining file:///.../chapter-31-professional-python/project/solution
Installing build dependencies: started
Installing build dependencies: finished with status 'done'
...
Building wheels for collected packages: taskbox
Building editable for taskbox (pyproject.toml): finished with status 'done'
Created wheel for taskbox: filename=taskbox-1.0.0-0.editable-py3-none-any.whl ...
Successfully built taskbox
Installing collected packages: taskbox
Successfully installed taskbox-1.0.0
taskbox only imports from the standard library: argparse, logging, json, pathlib, datetime. There is nothing to pin. The file is kept — not deleted — with a comment explaining that. An empty requirements.txt that says "nothing needed" is a deliberate, documented design choice; a missing requirements.txt just looks like someone forgot to write one.
Why this project matters
Every real Python tool you've used from a terminal — pip, black, pytest, git itself — is exactly this shape: subcommands parsed by something like argparse, logic separated from the argument-parsing layer, logging instead of scattered print()s so verbosity is a flag instead of a code edit, and a packaging file that makes pip install turn a folder of .py files into a real command. This project is a small, honest version of that shape — the same one you'd scale up for a real internal tool at a job.
More project ideas
No starter/solution files are provided for these on purpose — building and verifying each one yourself is the point. Each is solvable with only what this chapter (and earlier chapters) have taught.
1 Wrap an earlier project's logic in a proper CLI
Scenario: You already built a menu-driven tool in an earlier chapter (e.g. the inventory tracker or a similar loop-based project) that reads input with input() in a while True: loop.
What to do: Rewrite it as a package with subcommands instead — inventory add, inventory list, inventory remove, etc. — using the same core.py/cli.py split this project uses. The underlying logic barely changes; only how a user reaches it does.
Suggested approach: Start by writing down what your old while True: menu options were — each menu option usually maps to exactly one subcommand.
2 Add a --config flag that reads defaults from a file
Scenario: Typing --priority high on every single taskbox add call gets old if you mostly add high-priority tasks.
What to do: Add a --config flag pointing at a small JSON (or .ini, using configparser) file with a default_priority key. Load it (if present) before parsing args, and use its value as the --priority default instead of the hardcoded "normal".
Suggested approach: argparse lets you build the parser's defaults dynamically before calling add_argument — read the config file first, then pass its value as default= for that argument.
3 Add a --dry-run flag
Scenario: Before deleting a task (or running any destructive command), it's useful to preview what would happen without actually changing anything.
What to do: Add a top-level --dry-run flag. When set, delete and done should print what they would do ("Would delete: #2 Buy groceries") without calling save_tasks.
Suggested approach: Thread the flag from args.dry_run down into core.py's functions as a parameter, and add an if dry_run: return ... early-exit right before the save_tasks call in each.
4 Publish it as a real installable package with a second entry point
Scenario: taskbox currently has one console script. Real CLI tools sometimes ship a second, shorter alias.
What to do: Add a second entry under [project.scripts] in pyproject.toml — e.g. tb = "taskbox.cli:main" — reinstall with pip install -e ., and confirm both taskbox and tb work identically. Then try pip uninstall taskbox and confirm both commands disappear.
Suggested approach: [project.scripts] is just a mapping of command-name → module:function — add as many keys as you want, they all point at the same main().