Sub topic 8
Writing useful help and usage text
This chapter assumes you can build a parser with add_argument and run it from main(argv). It covers how to make the -h output explain your tool.
Where argparse gets its text
argparse builds -h output from the arguments you declare, so it is always present. Whether it is useful depends on the text you supply.
usageis generated fromprogand your arguments. You rarely need to override it.descriptionappears below the usage line and says what the tool does.epilogappears at the end. Use it for examples or pointers to documentation.helpis a one-line explanation of a single argument.metavarreplaces the placeholder shown for a value.
A fully annotated parser
import argparse
def build_parser():
parser = argparse.ArgumentParser(
prog="backup",
description="Copy a directory to a backup location.",
epilog="Example:\n backup ./notes -d /tmp/out --level 3",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument("source", metavar="SOURCE_DIR",
help="directory to back up")
parser.add_argument("-d", "--dest", metavar="DIR", default="backups",
help="where to write the backup (default: %(default)s)")
parser.add_argument("--level", type=int, choices=range(1, 10),
default=6, metavar="N",
help="compression level, 1-9 (default: %(default)s)")
parser.add_argument("--debug", action="store_true",
help=argparse.SUPPRESS)
return parser
if __name__ == "__main__":
build_parser().print_help()The usage line this produces is:
usage: backup [-h] [-d DIR] [--level N] SOURCE_DIRWithout metavar, the placeholders would be DEST, LEVEL and source. Without it on --level, argparse would also print {1,2,3,4,5,6,7,8,9} for the choices, which is noise.
Techniques worth knowing
- Defaults in help. Write
%(default)sin the help string. argparse substitutes the real default, so the text cannot drift out of date. Other available names include%(prog)s,%(type)sand%(choices)s. - Hidden arguments.
help=argparse.SUPPRESSremoves an argument from both the usage line and the argument list. Use it for debugging switches. - Preserving layout. By default argparse rewraps all text to the terminal width.
RawDescriptionHelpFormatterkeeps your line breaks indescriptionandepilogbut still wraps argument help.RawTextHelpFormatterkeeps line breaks everywhere.ArgumentDefaultsHelpFormatterappends(default: ...)to every argument for you.
What good help text looks like
- Start with a lowercase verb or noun phrase and omit the final period, as in "directory to back up". This matches the style of
-hitself. - State units and ranges: "timeout in seconds", "compression level, 1-9".
- Describe what the argument does, not its name. "number of retries" is better than "the retries option".
- Put one or two realistic examples in the epilog. Learners copy them.
Exercise
A parser has parser.add_argument("--rate", type=int, default=10, help="requests per second (default: 10%)"). What happens when the user runs -h, and how do you fix it?
Show answer
argparse formats the help string with % substitution, so the bare % raises an error (a ValueError about an unsupported format character) when help is displayed. Escape it as 10%%. Better, write (default: %(default)s) so the text always matches the real default.