Sub topic 6
Converting and validating values
This chapter assumes you can build a parser with add_argument, read the resulting Namespace, and run a script from a shell. You should also know what an exit code is. Here you will learn how argparse turns raw text into Python values and how to reject bad input with clear messages.
Everything starts as a string
The operating system gives your program a list of strings. argparse converts each value with the type argument of add_argument. Without type, the value stays a str.
type is any callable that takes one string and returns the converted value. It does not have to be a class. int, float, pathlib.Path, and your own functions all work.
import argparse
parser = argparse.ArgumentParser(prog="demo")
parser.add_argument("--count", type=int, default=1)
parser.add_argument("--ratio", type=float)
args = parser.parse_args(["--count", "3", "--ratio", "0.5"])
print(repr(args.count), repr(args.ratio))This prints 3 0.5, an int and a float. If the text cannot be converted, argparse prints the usage line and an error to stderr, then exits with status 2:
usage: demo [-h] [--count COUNT] [--ratio RATIO]
demo: error: argument --count: invalid int value: 'many'Your own code never sees the bad value, because the program stops before parse_args returns.
The conversion pipeline
The order of steps matters when you combine type, choices, and default.
Two consequences follow from this order:
choicesis compared against the converted value, not the original text. Withtype=int, choices=[1, 2, 3], the user types2, and argparse checks the integer2.- An error from
typestops the pipeline beforechoicesruns.
Custom type functions
A custom converter has one job: return a good value, or raise an exception. How you raise it controls the message.
| Exception raised | Message the user sees |
|---|---|
| `ValueError` or `TypeError` | A generic message: `invalid NAME value: 'text'`, where NAME is the function's `__name__` |
| `argparse.ArgumentTypeError` | Your own text, used as written |
| Any other exception | A traceback, because argparse does not catch it |
Use ArgumentTypeError whenever you want to explain what is wrong.
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)
parser.parse_args(["--port", "70000"])The last line prints serve: error: argument --port: 70000 is outside 1-65535 and exits with status 2.
The generic path is a convenient shortcut. A function named percent that raises ValueError produces invalid percent value: '150', so choose function names with that in mind.
import argparse
def percent(text):
value = float(text)
if not 0 <= value <= 100:
raise ValueError(text)
return value
parser = argparse.ArgumentParser(prog="demo")
parser.add_argument("--ratio", type=percent)
parser.parse_args(["--ratio", "150"])Validating files and paths
argparse.FileType opens a file during parsing. This has drawbacks. The file is opened before your program decides it needs it, nothing guarantees it gets closed, and errors surface as parse errors. Prefer a converter that returns a Path, and open the file later in your own code.
import argparse
from pathlib import Path
def existing_file(text):
path = Path(text)
if not path.is_file():
raise argparse.ArgumentTypeError(f"{text!r} is not a file")
return path
parser = argparse.ArgumentParser(prog="count-lines")
parser.add_argument("source", type=existing_file)The check happens at parse time, which gives a friendly error. It can still go stale, because the file may be deleted before you open it. Handle OSError when you open the file as well.
Restricting values with choices
choices accepts any container. Invalid input produces an error that lists the allowed values.
import argparse
parser = argparse.ArgumentParser(prog="serve")
parser.add_argument(
"--level",
type=str.lower,
choices=["debug", "info", "warning"],
default="info",
)
parser.add_argument("--workers", type=int, choices=range(1, 9), metavar="N")
args = parser.parse_args(["--level", "DEBUG", "--workers", "4"])
print(args.level, args.workers)This prints debug 4. Here type=str.lower normalizes the text before choices compares it, so users can type DEBUG.
The metavar="N" on --workers matters. Without it, the help text lists every value in range(1, 9) inside the usage line. For large ranges that is unreadable, so give the argument a short metavar and describe the range in help.
Defaults and conversion
A default that is a string is passed through type, as if the user had typed it. A default of any other type is used as is.
import argparse
parser = argparse.ArgumentParser(prog="demo")
parser.add_argument("--a", type=int, default="10")
parser.add_argument("--b", type=int, default=10)
parser.add_argument("--c", type=int, default=None)
args = parser.parse_args([])
print(repr(args.a), repr(args.b), repr(args.c))This prints 10 10 None. The string "10" became an integer, and None was left alone. This is why a None default is a reliable way to detect "the user did not supply this option". Note that choices is not checked against non-string defaults either.
Multiple values
When nargs collects several values, type is applied to each one separately, and you get a list.
import argparse
parser = argparse.ArgumentParser(prog="resize")
parser.add_argument("--size", type=int, nargs=2, metavar=("WIDTH", "HEIGHT"))
print(parser.parse_args(["--size", "640", "480"]).size)This prints [640, 480]. The error message for a bad item names the option and the offending item, so users can find the problem.
The boolean trap
type=bool does not work as expected. bool("False") is True, because any non-empty string is true. Your parser would accept --debug False and turn debugging on.
import argparse
parser = argparse.ArgumentParser(prog="demo")
parser.add_argument("--debug", type=bool)
print(parser.parse_args(["--debug", "False"]).debug)This prints True. Use action="store_true" for a plain flag. If you want paired --cache and --no-cache switches, Python 3.9 and later provide argparse.BooleanOptionalAction:
import argparse
parser = argparse.ArgumentParser(prog="demo")
parser.add_argument("--cache", action=argparse.BooleanOptionalAction, default=True)
print(parser.parse_args(["--no-cache"]).cache)This prints False.
Checks that involve several arguments
A type function sees one string only. Rules that compare two values, such as a start that must not exceed an end, belong after parsing. Call parser.error(message). It prints the usage line, writes prog: error: message to stderr, and exits with status 2, the same as a built-in failure.
import argparse
def build_parser():
parser = argparse.ArgumentParser(prog="window")
parser.add_argument("--start", type=int, default=0)
parser.add_argument("--end", type=int, required=True)
return parser
def main(argv=None):
parser = build_parser()
args = parser.parse_args(argv)
if args.start > args.end:
parser.error("--start must not be greater than --end")
print(f"range {args.start}..{args.end}")
return 0
if __name__ == "__main__":
raise SystemExit(main())Running main(["--start", "5", "--end", "2"]) exits with status 2 and the message you wrote. Keeping parser in a local variable inside main is what makes this possible.
Common errors
- Writing
type=int()instead oftype=int. You must pass the callable, not call it. - Using
type=boolfor a switch. Usestore_trueorBooleanOptionalAction. - Raising
ValueErrorin a converter and wondering why the message is generic. RaiseArgumentTypeError. - Expecting
choicesto see the original text. It sees the converted value. - Passing a negative number such as
-5as a value. argparse may read it as an option. Write--offset=-5, which is always unambiguous. - Doing cross-argument checks inside
type. Do them afterparse_argswithparser.error.
Exercise
Write a type function key_value for an option --set that accepts text like retries=3 and returns the tuple ("retries", "3"). It must reject text with no = or with an empty key, and the user must see a clear message. Which exception do you raise, and why?
Show answer
Raise argparse.ArgumentTypeError, because it lets you control the message shown to the user. import argparse def keyvalue(text): key, sep, value = text.partition("=") if not sep or not key: raise argparse.ArgumentTypeError(f"{text!r} must look like KEY=VALUE") return key, value A ValueError would work, but the message would be the generic "invalid keyvalue value: ..." and would not explain the expected format.
Exercise
A parser defines --level with type=str.lower and choices=["debug", "info"]. The user passes --level INFO. What is stored in args.level, and what happens with --level verbose?
Show answer
"info" is stored, because type lowercases the text before choices compares it. With "verbose", the lowercased value is not in choices, so argparse prints an invalid choice error that lists the allowed values and exits with status 2.