Types and defaults

argparse · Essentials · 8 min

Everything on the command line is a string; converting early gives clean errors and simple code.

Command-line arguments arrive as strings. type= names a callable that converts each one: type=int, type=float, type=pathlib.Path. If conversion raises ValueError or TypeError, argparse reports a friendly usage error such as argument -n: invalid int value: 'x' instead of a traceback.

default= sets the value used when an option is absent. String defaults are passed through type too, so default="8080" with type=int gives the int 8080; non-string defaults are used as is.

In help text, %(default)s inserts the default, so the help stays accurate:

p.add_argument("--port", type=int, default=8080, help="port (default: %(default)s)")

Or pass formatter_class=argparse.ArgumentDefaultsHelpFormatter to the parser to append defaults to every help line automatically.

Avoid type=bool: bool("False") is True, because any non-empty string is truthy. Use a flag action instead (next lesson). Similarly, type=open opens files at parse time and leaves them open on errors; take a Path and open it yourself with a with block.

Example

import argparse
from pathlib import Path

p = argparse.ArgumentParser(prog="serve")
p.add_argument("root", type=Path)
p.add_argument("--port", type=int, default=8080, help="port (default: %(default)s)")
p.add_argument("--ratio", type=float, default="0.5")   # string default is converted

a = p.parse_args(["site"])
print(repr(a.root), a.port, a.ratio)   # PosixPath('site') 8080 0.5
print(p.parse_args(["site", "--port", "9000"]).port + 1)   # 9001

try:
    p.parse_args(["site", "--port", "http"])
except SystemExit as e:
    print("exit status", e.code)
# serve: error: argument --port: invalid int value: 'http'  (stderr)
# exit status 2

Remember

  • type= converts each value; conversion errors become usage errors
  • String defaults are converted by type too
  • Never use type=bool

Watch out for

  • type=bool, which turns '--debug False' into True.

Check yourself

  1. With add_argument('--n', type=int, default='3'), what is args.n when --n is not given?

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#type