Writing good help output

argparse · Practical · 8 min

Help text is your CLI's documentation; users read it before anything else.

argparse builds --help from what you declare, so a little effort pays off:

  • ArgumentParser(description=..., epilog=...): text before and after the argument list. Use the epilog for examples.
  • help= on each argument: one short phrase. %(default)s, %(type)s, %(choices)s and %(prog)s are substituted.
  • metavar=: the placeholder name in usage, such as --output FILE instead of --output OUTPUT. A tuple names each value for nargs=N.
  • help=argparse.SUPPRESS hides an argument from help entirely.

Formatter classes change layout:

  • RawDescriptionHelpFormatter keeps your line breaks in description and epilog (by default text is re-wrapped).
  • RawTextHelpFormatter keeps line breaks in argument help too.
  • ArgumentDefaultsHelpFormatter appends "(default: ...)" automatically.
  • MetavarTypeHelpFormatter uses type names as metavars.

You can combine two with multiple inheritance in a tiny subclass.

Since 3.13, add_argument(..., deprecated=True) and add_parser(..., deprecated=True) let you keep an old option working while printing a deprecation warning when it's used. In 3.13 the usage line no longer repeats the metavar for options with short and long forms (-o, --output FILE).

Example

import argparse

class Fmt(argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter):
    pass

p = argparse.ArgumentParser(
    prog="resize", formatter_class=Fmt, description="Resize images.",
    epilog="examples:\n  resize photo.jpg --width 800")
p.add_argument("image", help="input image")
p.add_argument("-w", "--width", type=int, default=1024, metavar="PX", help="target width")
p.add_argument("--quality", type=int, default=85, help=argparse.SUPPRESS)
p.add_argument("--old-flag", action="store_true", deprecated=True, help="use --width")
p.print_help()
p.parse_args(["x.jpg", "--old-flag"])
# usage: resize [-h] [-w PX] [--old-flag] image
# ...
#   -w, --width PX  target width (default: 1024)
# ...
# examples:
#   resize photo.jpg --width 800
# resize: warning: option '--old-flag' is deprecated   (stderr)

Remember

  • description, epilog and per-argument help build --help
  • metavar names placeholders; SUPPRESS hides arguments
  • Formatter classes control wrapping and default display; deprecated= is new in 3.13

Watch out for

  • Writing multi-line examples in the epilog without RawDescriptionHelpFormatter; argparse re-wraps them into one paragraph.

Check yourself

  1. Your epilog's example lines are merged into one paragraph in --help. What fixes it?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.python.org/3/library/argparse.html#formatter-class

Builds on

Unlocks

Nothing builds on this yet.