Batu Lab NotesPractical developer guides

Design a file-processing CLI around explicit modes

By Batu ยท English technical notes

Also published in our Blogger archive.

Require a subcommand to select the operation

add_subparsers stores the chosen command in mode, and required=True makes no-mode invocations argparse usage errors. add_parser registers inspect, so the explicit argv produces mode equal to inspect. Dispatch can therefore use an operation name rather than infer intent from optional flags.

This parser defines neither inspect options nor a handler. Put those requirements on the inspect subparser so a future mode does not inherit unrelated validation.

Example

from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as d:
    import argparse
    p = argparse.ArgumentParser()
    s = p.add_subparsers(dest='mode', required=True)
    s.add_parser('inspect')
    assert p.parse_args(['inspect']).mode == 'inspect'
    result = 'mode=inspect'
    print(result)

Expected stdout:

mode=inspect

Sources

- argparse.ArgumentParser.add_subparsers

Prepared with AI assistance. The example uses synthetic data; its stated limits apply.