Skip to content

Lesson 1 of 9 · 22m

argparse: Design the Contract Before the Parser

Use argparse deliberately: commands, positional arguments, options, defaults, validation, and help text form the public API of your tool.

The worst CLI interfaces are not built; they accumulate. One script gains --input, another gains -i, a third accepts a bare filename, and six months later nobody can write a cron job without reading source code. Treat the parser as API design. argparse is in the standard library, battle-tested, and good enough for most single-purpose tools.

Parse at the edge, pass values inward

import argparse


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="logscan",
        description="Summarize authentication failures in journald JSON exports.",
    )
    parser.add_argument("paths", nargs="+", help="journal export files to scan")
    parser.add_argument("--since", metavar="YYYY-MM-DD", help="ignore older entries")
    parser.add_argument("--format", choices=("text", "json"), default="text")
    parser.add_argument("-v", "--verbose", action="count", default=0)
    return parser


def main(argv=None):
    args = build_parser().parse_args(argv)
    ...

main(argv=None) is important: tests can pass a list, while production uses sys.argv. Do not let parser objects, namespaces, or stringly-typed flags leak through the application. Convert once, then pass ordinary values.

Positional arguments are nouns; options are modifiers

A positional argument should be the object the command acts on: files, hosts, users. Flags should modify behavior: --since, --dry-run, --format json. If users regularly type three flags to express one action, the command shape is probably wrong.

Use explicit types and constrained choices when possible:

parser.add_argument("--workers", type=int, default=4)
parser.add_argument("--level", choices=("debug", "info", "warning"), default="info")

type=int rejects --workers nope before your business logic runs. choices produces useful help automatically and prevents a dozen misspellings from becoming supported behavior.

Mutually exclusive flags need explicit structure

output = parser.add_mutually_exclusive_group()
output.add_argument("--json", action="store_true")
output.add_argument("--quiet", action="store_true")

Without this, users can supply contradictory input and you have to invent precedence. CLIs become dependable when invalid combinations fail immediately with exit status 2.

Help text is part of the implementation

Write help for the person holding the pager at 2 a.m. Say what values mean, not what type they are: --since YYYY-MM-DD ignore entries before this UTC date. Add examples in epilog when invocation is non-obvious.

Field notes

  • Never require a flag for information already obvious from context; defaults should make the common case short.
  • nargs="*" for required input creates confusing empty-invocation behavior. Prefer nargs="+" when at least one item is required.
  • Do not use type=open; it opens files before validation finishes and makes cleanup awkward. Parse paths, then open them inside the command.
  • A parser error exits with status 2. Preserve that convention; scripts use it to distinguish bad invocation from runtime failure.

Was this lesson helpful?

Sign in to rate