Sub topic 6
Converting and validating values
This chapter assumes you can write a basic ArgumentParser, add positional arguments and options, and read the resulting namespace. It covers how argparse turns text into Python values and how to reject bad input before your program logic runs.
Everything arrives as a string
The shell passes every argument to Python as a string. Unless you say otherwise, args.count is "3", not 3. The type keyword tells argparse which callable to run on the string. Any callable that takes one string and returns a value will work: int, float, pathlib.Path, or your own function.
import argparse
parser = argparse.ArgumentParser(prog="repeat")
parser.add_argument("--count", type=int, default=1)
parser.add_argument("--ratio", type=float, default=0.5)
args = parser.parse_args(["--count", "3"])
print(args.count, type(args.count).__name__)If the conversion raises ValueError or TypeError, argparse prints a usage message with invalid int value: 'many' and exits with status 2. You do not write any try block for this.
Defaults are converted too
When a default is a string, argparse runs it through type. A default that is already the right type is left alone. Keep this in mind if your default is something like "8000" and your type function has side effects.
Restricting values with choices
choices limits a value to a fixed set. Argparse checks it after conversion, and it lists the allowed values in the error message and in --help.
parser.add_argument("--level", choices=["debug", "info", "warning"], default="info")Use choices for small, fixed sets. For a range such as ports, write a validator.
Custom validators
A custom type function converts and validates in one step. Raise argparse.ArgumentTypeError with a readable message. Argparse shows the message as the error text.
import argparse
def port(value):
try:
number = int(value)
except ValueError:
raise argparse.ArgumentTypeError(f"{value!r} is not an integer")
if not 1 <= number <= 65535:
raise argparse.ArgumentTypeError(f"{number} is outside 1-65535")
return number
parser = argparse.ArgumentParser(prog="serve")
parser.add_argument("--port", type=port, default=8000)
print(parser.parse_args(["--port", "8080"]).port)Running with --port 70000 prints serve: error: argument --port: 70000 is outside 1-65535 and exits with status 2.
Common errors
- Using
type=bool.bool("False")isTrue, because any non-empty string is true. Useaction="store_true"for flags, or write a function that parses the words you accept. - Letting other exceptions escape. Argparse catches only
ArgumentTypeError,TypeErrorandValueErrorfrom a type function. Any other exception becomes a traceback. Convert it toArgumentTypeErroryourself. - Validating relations between arguments in
type. A type function sees one value at a time. To check that--startis less than--end, do it after parsing and callparser.error("..."), which gives the same usage message and exit status 2. - Opening files in a type function.
type=argparse.FileTypeopens the file at parse time and leaves closing it to you. Prefertype=pathlib.Pathand open the file insidemain.
Exercise
Write a type function positive_int that accepts "5" and rejects "0", "-2" and "abc" with an ArgumentTypeError. What exit status does argparse use when it rejects a value?
Show answer
def positiveint(value): try: number = int(value) except ValueError: raise argparse.ArgumentTypeError(f"{value!r} is not an integer") if number < 1: raise argparse.ArgumentTypeError(f"{number} is not positive") return number Use it with `parser.addargument("--n", type=positive_int)`. Argparse exits with status 2 after printing the usage message and the error text to stderr.
Exercise
Why does parser.add_argument("--debug", type=bool) behave incorrectly when the user passes --debug False?
Show answer
The type callable receives the string "False", and bool("False") is True because the string is non-empty. Use action="store_true" instead.