🐍 Python for Everyone

← Back to the project

Chapter 31 — Solo → AI-Paired → Critique 25 min

Now Pair With an AI

Step 1: You already built this solo

You just built taskbox yourself, unaided — a packaged CLI tool with subcommands, real logging, and a working pip install -e .. That project is unchanged; this page is additive. Now imagine a more common real-world starting point: you already have a plain, working script (no argparse, no logging, no packaging) and you ask an AI assistant to "professionalize" it in one pass — the way developers actually reach for an assistant on a Friday afternoon, wanting the boring wiring done fast.

Step 2: Now pair with an AI

Here's a real prompt a learner could give an AI assistant, starting from a plain script instead of from scratch:

the-prompt.txt
I have a single-file Python script that manages a to-do list in a
JSON file using print() statements and a few hardcoded if/elif
branches on sys.argv. Add argparse and logging to it and make it a
proper CLI tool with subcommands (add, list, done, delete), a
--verbose flag, and package it with a pyproject.toml so I can
`pip install -e .` it and get a `taskbox` command. Please just
give me the full working files.

And here's a plausible response — the kind of complete, confident-looking output an AI assistant might hand back on the first try. Read it the way you'd review a pull request from a teammate who moved fast, before scrolling to the critique below.

taskbox/cli.py (AI output)
import argparse
import logging
from taskbox.core import add_task, list_tasks, complete_task, delete_task

# Set up logging for the whole app
logging.basicConfig(
    level=logging.DEBUG,
    format="%(levelname)s: %(message)s",
)
logger = logging.getLogger(__name__)


def build_parser():
    parser = argparse.ArgumentParser(prog="taskbox")
    parser.add_argument("--file", default="tasks.json")
    parser.add_argument("-v", "--verbose", action="store_true",
        help="enable verbose output")

    subparsers = parser.add_subparsers(dest="command")

    add_parser = subparsers.add_parser("add", help="add a new task")
    add_parser.add_argument("--title", default="Untitled task",
        help="the task title")
    add_parser.add_argument("--priority", default="normal")

    list_parser = subparsers.add_parser("list", help="list tasks")
    list_parser.add_argument("--all", action="store_true")

    done_parser = subparsers.add_parser("done", help="mark a task done")
    done_parser.add_argument("id", type=int)

    delete_parser = subparsers.add_parser("delete", help="delete a task")
    delete_parser.add_argument("id", type=int)

    return parser


def main():
    parser = build_parser()
    args = parser.parse_args()

    if args.command == "add":
        task = add_task(args.file, args.title, args.priority)
        print(f"Added task #{task['id']}: {task['title']}")
    elif args.command == "list":
        for task in list_tasks(args.file, show_done=args.all):
            print(task)
    elif args.command == "done":
        complete_task(args.file, args.id)
    elif args.command == "delete":
        delete_task(args.file, args.id)


if __name__ == "__main__":
    main()
pyproject.toml (AI output)
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"

[project]
name = "taskbox"
description = "A small command-line task manager backed by a JSON file."
requires-python = ">=3.9"

[project.scripts]
taskbox = "taskbox.cli:main"

[tool.setuptools]
packages = ["taskbox"]

It's complete, imports cleanly, and looks like exactly the kind of fast, thorough answer you asked for — subcommands, a --verbose flag, a real pyproject.toml. It's also wrong in three separate, genuinely subtle ways.

Step 3: Where did the AI's code lie to you?

Click to see the critique

What it looks like it does: "set up logging for the whole app" reads like a reasonable one-time setup step — and the -v/--verbose flag is right there in the parser, so it looks wired up.

What it actually does: two separate problems in one call. First, logging.basicConfig() configures the root logger — every library taskbox imports (or ever will import) that uses logging.getLogger(__name__) without its own handler flows into this same root configuration. The moment taskbox depends on anything with its own internal debug logging, --verbose was never even necessary to see it: DEBUG is hardcoded at import time, so everything's debug output prints, always, whether the user asked for verbose or not. Second, the args.verbose flag the parser collects is never actually read anywhere — the flag exists in --help and does genuinely nothing.

Why it matters: confirmed by actually running an equivalent setup against a small fake dependency with its own debug-level logger: basicConfig(level=logging.DEBUG) at import time printed that dependency's internal "opened connection pool" / "retry loop" debug lines right alongside taskbox's own, with no way to turn them off short of editing code. On a real tool with real dependencies (a database driver, an HTTP client), this is exactly how a "quiet" default run turns into an unreadable wall of unrelated internal noise.

The fix: configure a named logger (logging.getLogger("taskbox")), attach a handler to it directly, set propagate = False so its records don't also flow to the root logger, and actually branch the level on args.verbose (DEBUG if true, else INFO) instead of hardcoding it — see this chapter's own solution/taskbox/cli.py for the working version.

What it looks like it does: add_parser.add_argument("--title", default="Untitled task", ...) looks like a helpful convenience — a default so the command "just works" even if you forget to type a title.

What it actually does: the prompt never asked for an optional title with a fallback — a to-do item genuinely has no meaningful default. Confirmed by actually running it: taskbox add with no title at all parses successfully and silently creates a real task named "Untitled task" — no error, no warning, exit code 0. The user who forgot --title "Buy milk" gets a task list quietly polluted with a placeholder entry instead of an argparse error telling them what they forgot.

Why it matters: this is the exact inversion CONTRIBUTING.md's argparse guidance warns about — something that should be a required positional argument (there's no sensible default for "what is this task called") became an optional flag with a default that's wrong for every real use, and the failure is silent rather than loud. A learner skimming --help output would see --title TITLE and assume it's optional the same way --priority genuinely is, with no way to tell the two apart from the help text alone.

The fix: make it a required positional argument — add_parser.add_argument("title", help="the task's title (required, positional)"), with no default at all. Then taskbox add with nothing after it fails loudly with argparse's own "the following arguments are required: title" message and exit code 2, which is what should happen.

What it looks like it does: the file has [build-system], [project] with a name and description, [project.scripts] wiring the entry point, and [tool.setuptools] — it reads as complete and standard-shaped.

What it actually does: confirmed by actually running pip install -e . against this exact file — it fails during the build step with ValueError: invalid pyproject.toml config: \`project\`. configuration error: \`project\` must contain ['version'] properties. The [project] table requires either a static version key or an explicit dynamic = ["version"] declaration (paired with a way to compute it, like [tool.setuptools.dynamic]) — a bare [project] table with no version at all is invalid per the packaging spec, not optional-but-recommended.

Why it matters: the error is thrown by a build subprocess several layers down (setuptools.config.pyprojecttoml), with a message that doesn't say "you forgot version" in plain language — it says "configuration error" and names the field in spec terminology. A learner pasting this pyproject.toml in good faith, trusting that AI-generated packaging config is correct because it "looks standard," hits a wall of subprocess traceback with no obvious next step.

The fix: add version = "1.0.0" (or whatever version) directly under [project]. This chapter's own solution/pyproject.toml has it — verified with a real pip install -e . that completed successfully and produced a working taskbox command.

Step 4: Your entry for this chapter's playbook

Fill this in for yourself — it's not saved or sent anywhere, just yours to keep (copy it into your own notes before you close this tab).

← Back to the Project All Chapters →