Full name: argparse: a coined name from argument and parse; it is not an abbreviation.
Definition
argparse is the module of Python’s §12.23 standard library that turns a program’s command-line arguments, the words typed after the program’s name, into named values. The program declares each argument it accepts: its name, how to convert its text, for example to an integer, its allowed values and its default. parse_args() then checks every argument against its own declaration, fills in the default of every argument not given, and on any mismatch prints a usage message and exits with status 2. Relations between arguments are left to the program.
The idea
A tool that erases and reprograms a device accepts --erase, --device, --min and --max. Every argument arrives as a text string. Converting and checking these strings by hand, with clear error messages and a help text, is repetitive and easy to get wrong; argparse does it from declarations. The dangerous mistakes, however, often lie in combinations: --erase with no --device, so that some default chooses the device, or --min 10 --max 5. Each argument is well formed on its own, and only the combination is wrong.
argparse works like the checks on the boxes of a paper form. Each box has a format, such as a number or one of a list of options, and a blank box gets a pre-printed value. A form can pass every box check and still be inconsistent, such as an end date before the start date, and nobody checks the pre-printed values at all. A program therefore has three gates between the command line and an action: syntax, which argparse checks; consistency and meaning, which code after parse_args() must check; and permission, the authorization §1.7 check that this user may perform this action on this target. The form picture stops at one point: argparse can check one relation itself, that at most one option of a declared group is given.
How it works
A program creates parser = argparse.ArgumentParser() and declares each argument with one parser.add_argument(...) call. The main parameters:
The name.
"path"declares a positional argument, identified by its position;"--max"declares an optional argument, identified by its name.type: a function that turns the text into a value, such asint. If it raisesValueError,TypeErrororargparse.ArgumentTypeError, the argument is rejected.choices: the allowed values, compared after conversion.default: the value used when the argument is absent; if none is declared, it isNone, orFalsefor a flag declared withstore_true.required=True: the argument must be given.action="store_true": a flag that takes no value and setsTrue.
parser.add_mutually_exclusive_group() creates a group of options of which at most one may be given, or exactly one when the group is created with required=True.
A call args = parser.parse_args() then:
reads the strings that follow the program name,
sys.argv[1:];matches each option string to a declared option, accepting any unambiguous prefix of a long option, so that
--dryselects--dry-run, unless the parser was created withallow_abbrev=False;converts each value with its
typefunction and checks the result against itschoices;checks that every required argument appeared, that no undeclared argument appeared, and that no mutually exclusive group has two members given;
sets every argument that was not given to its default, converting a default that is a string with
typeas if it had been typed, and using any other default as it is;returns a
Namespaceobject with one attribute per argument, such asargs.max.
On a failure in steps 2 to 4, argparse prints a usage line and an error message to the diagnostic output stream (stderr) and ends the program with exit status §13.24 2. The option -h or --help prints the help text and exits with status 0.
After parse_args() returns, and before any action, the program:
computes the effective value of every argument, including defaults and any value taken from an environment variable or a configuration file;
checks every relation it depends on, such as or “
--eraserequires--device”;checks the meaning of each value: a number within the range the program can afford, a path that names an existing file of the expected kind once symbolic links §13.10 are followed;
reports a failed check with
parser.error(message), which prints the usage line and the message and exits with status 2, like argparse’s own errors;checks authorization immediately before the action;
records the effective values in its output or log, so that a value chosen by a default is visible.
Worked example
The declarations:
p.add_argument("--min", type=int, default=0)
p.add_argument("--max", type=int, default=16)
p.add_argument("--level", type=int, choices=[1, 2, 3], default=5)
p.add_argument("--erase", action="store_true")
p.add_argument("--device")
The program requires , requires the level to be 1, 2 or 3, and must never erase without a named device.
--min 10 --max 5.int("10")is 10 andint("5")is 5. Both conversions succeed, soparse_argsreturnsmin=10andmax=5. The check is false, so the program callsp.error("--min (10) is greater than --max (5)"), which exits with status 2 before anything is erased.--min 20. The user never typed--max, somaxhas its default, 16, and is false. The check catches this only because it runs on the effective values. Its message should say that 16 is the default, or the user sees an error about an option they never gave.No arguments.
levelis the default 5, although the choices are 1, 2 and 3. argparse checks choices only for values given on the command line, so the default passes unnoticed; Python 3.12 behaves this way. The check after parsing catches it.--erasealone.eraseisTrueanddeviceis its default,None. Each value is valid on its own. A program that went on to erase “the first device found” would act on a target nobody chose. The relation check “eraserequiresdevice” rejects the command.
Stated precisely
Let be the list of argument strings. For each declared argument that takes one value, let , and be its conversion function, allowed values and default, and write for the value of in the returned namespace . If parse_args(L) returns , then:
if appeared in with the string , then , and is in when choices were declared;
if did not appear, then when the default is a string and otherwise; in Python 3.12 neither case is checked against the choices;
every required argument appeared in , and no mutually exclusive group had two members in .
Otherwise parse_args prints an error and raises SystemExit with status 2.
parse_args establishes nothing else. Let be the program’s validity condition: every relation between arguments, every range and every meaning that the action depends on. The program must evaluate on the effective values after parse_args returns and before the first effect, and stop with an error when is false. Authorization is a separate condition, decided from who the user is and what the action touches, not from the syntax of the command line.
Limits and common mistakes
type=int accepts any integer, negative or very large. Python’s int also accepts surrounding spaces and underscores between digits, so "1_000" becomes 1000. A range needs choices or an explicit check.
Conversion functions run during parsing, before any check written after parse_args. argparse.FileType("w") opens the named file while parsing, which creates it or empties it, even if a later argument then fails. The Python documentation deprecates FileType from version 3.14 and advises opening files after parsing. Conversion functions should have no side effects.
Prefix matching can select an option the user did not mean. If a tool has --delete-all and no other option that starts with --del, then --del selects --delete-all. Adding an option later can also make a prefix that used to work ambiguous. A tool with destructive options should pass allow_abbrev=False.
A default is a decision nobody typed. A default that comes from an environment variable or a configuration file changes what the program does without appearing on the command line. A destructive action should refuse to run unless its target was given explicitly; refusing is then the secure default §1.47.
Parsing is not authorization. --output /etc/passwd is a well-formed argument. Whether this user may write there, and which file the path names once symbolic links are followed, are questions for checks after parsing.
A parser shared between programs is a shared interface: changing its defaults or conversion functions changes what every program that uses it accepts.
Questions answered
Are dangerous combinations or implicit defaults validated after parsing?
argparse does not validate them: it checks each argument against its own declaration, and the only relation between arguments it checks is the at-most-one rule of a mutually exclusive group. It does not check that --min is at most --max, that --erase comes with --device, or that a default lies within the declared choices. It fills in defaults silently, without the choices check that it applies to typed values.
The program must therefore validate them itself, after parse_args() returns and before any effect. It computes the effective value of every argument, including defaults and values from the environment; checks every relation and range that the action depends on; rejects a dangerous combination with parser.error(), which exits with status 2; requires an explicit target for a destructive action; and checks authorization separately, immediately before acting.
Related entries: Authorization (§1.7), subprocess (§12.40), Boundary-value testing (§10.31), Transitive dependency (§10.43), Exit status (§13.24), Secure default (§1.47). Further reading: [127].