Sub topic 2
Actions, Validation, and a Testable `argparse` Program
Assume you can run Python scripts, define functions, and use a terminal. An argparse action controls how a parser stores an argument.
Actions: booleans, counters, and repeated options
Use store_true for a boolean flag. Its value is False unless the user provides the flag. Use count when repeating a flag should increase a number. Use append when an option can appear several times.
import argparse
def build_parser():
parser = argparse.ArgumentParser(
prog="report",
description="Create a project report.",
epilog="Example: report data.csv --verbose --tag urgent --tag weekly",
)
parser.add_argument("file", metavar="FILE", help="input CSV file")
parser.add_argument("--dry-run", action="store_true",
help="show what would happen")
parser.add_argument("-v", "--verbose", action="count", default=0,
help="increase detail; repeat for more detail")
parser.add_argument("--tag", action="append", default=[],
help="attach a tag; may be repeated")
return parser
def main(argv=None):
parser = build_parser()
args = parser.parse_args(argv)
print(f"Reading {args.file}")
print(f"Verbosity: {args.verbose}")
print(f"Tags: {args.tag}")
if args.dry_run:
print("No changes will be made.")
return 0
if __name__ == "__main__":
raise SystemExit(main())For example, report data.csv -vv --tag urgent --tag weekly produces a verbosity value of 2 and a tag list containing two strings.
Converting and validating values
The type parameter converts text before your program receives it. choices restricts a converted value to a fixed set.
parser.add_argument("--retries", type=int, default=3, metavar="N")
parser.add_argument("--format", choices=["text", "json"], default="text")For a range or rule, write a custom type function that raises argparse.ArgumentTypeError. argparse then prints a usage message and exits with status 2.
Multiple values, defaults, and required options
Use nargs="+" for one or more values and nargs="*" for zero or more. Use required=True sparingly, because positional arguments are usually clearer for essential input.
parser.add_argument("--files", nargs="+", required=True, metavar="FILE")Writing useful help and usage text
Give every public argument a short help string. Use metavar to replace technical placeholder names such as VALUE. description explains the command, while epilog can show a realistic example.
Structuring around `main(argv)`
Passing an explicit argument list makes the program easy to test. Production execution uses None, which means argparse reads sys.argv.
Exercise
Which action should you use for an option that may appear several times and should produce a list?
Show answer
Use action="append".