Section 12.37

argparse

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:

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:

  1. reads the strings that follow the program name, sys.argv[1:];

  2. matches each option string to a declared option, accepting any unambiguous prefix of a long option, so that --dry selects --dry-run, unless the parser was created with allow_abbrev=False;

  3. converts each value with its type function and checks the result against its choices;

  4. checks that every required argument appeared, that no undeclared argument appeared, and that no mutually exclusive group has two members given;

  5. sets every argument that was not given to its default, converting a default that is a string with type as if it had been typed, and using any other default as it is;

  6. returns a Namespace object with one attribute per argument, such as args.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:

  1. computes the effective value of every argument, including defaults and any value taken from an environment variable or a configuration file;

  2. checks every relation it depends on, such as 𝚖𝚒𝚗≤𝚖𝚊𝚡\texttt{min} \le \texttt{max} or “--erase requires --device”;

  3. 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;

  4. 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;

  5. checks authorization immediately before the action;

  6. 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 𝚖𝚒𝚗≤𝚖𝚊𝚡\texttt{min} \le \texttt{max}, requires the level to be 1, 2 or 3, and must never erase without a named device.

  1. --min 10 --max 5. int("10") is 10 and int("5") is 5. Both conversions succeed, so parse_args returns min=10 and max=5. The check 10≤510 \le 5 is false, so the program calls p.error("--min (10) is greater than --max (5)"), which exits with status 2 before anything is erased.

  2. --min 20. The user never typed --max, so max has its default, 16, and 20≤1620 \le 16 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.

  3. No arguments. level is 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 𝚕𝚎𝚟𝚎𝚕∈{1,2,3}\texttt{level} \in \{1, 2, 3\} after parsing catches it.

  4. --erase alone. erase is True and device is 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 “erase requires device” rejects the command.

Stated precisely

Let LL be the list of argument strings. For each declared argument xx that takes one value, let typex\mathrm{type}_x, choicesx\mathrm{choices}_x and defaultx\mathrm{default}_x be its conversion function, allowed values and default, and write N.xN.x for the value of xx in the returned namespace NN. If parse_args(L) returns NN, then:

Otherwise parse_args prints an error and raises SystemExit with status 2.

parse_args establishes nothing else. Let V(N)V(N) be the program’s validity condition: every relation between arguments, every range and every meaning that the action depends on. The program must evaluate V(N)V(N) on the effective values after parse_args returns and before the first effect, and stop with an error when V(N)V(N) 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].