Sub topic 3
Positional arguments
This chapter covers how argparse handles arguments identified by their position. It assumes you can write a function, run a script from a shell, and have read the previous chapter on creating a parser and calling parse_args.
What makes an argument positional
A positional argument is a value the user types without a flag, such as report.txt in cp report.txt backup.txt. The parser assigns it a meaning by its place among the other bare values. The first bare value goes to the first positional you declared, the second to the second, and so on.
You declare one by passing a name that does not start with a dash:
parser.add_argument("source")The name becomes the attribute on the result, so args.source holds the value. Three rules follow from this:
- A positional is required by default. If the user omits it, the parser prints the usage line and an error, then exits with status 2.
- The order of your
add_argumentcalls is the order the user must type the values in. - The value is a string unless you set
type.
A complete example
This tool copies one file to another. It uses two positionals and follows the main(argv=None) pattern from the Topic Spine.
import argparse
import shutil
import sys
from pathlib import Path
def build_parser():
parser = argparse.ArgumentParser(prog="cp-lite", description="Copy a file.")
parser.add_argument("source", type=Path, help="file to read")
parser.add_argument("destination", type=Path, help="file to write")
return parser
def main(argv=None):
args = build_parser().parse_args(argv)
try:
shutil.copyfile(args.source, args.destination)
except OSError as exc:
print(f"cp-lite: {exc}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())Running python cp_lite.py a.txt b.txt makes args.source equal to Path("a.txt") and args.destination equal to Path("b.txt"). Swapping the two values on the command line swaps their meaning, because only position distinguishes them.
What the parser says when something is missing
If the user types only one value, the parser reports the missing positional by name:
usage: cp-lite [-h] source destination
cp-lite: error: the following arguments are required: destinationThe usage line lists positionals in declaration order after the options. The error goes to stderr and the exit status is 2. Because parse_args raises SystemExit here, a test must catch that exception. The testing chapter covers this.
Extra values fail the same way. A third bare value produces unrecognized arguments: c.txt.
Names, `dest` and `metavar`
For a positional, the name you pass is the dest, the attribute name on the result. You cannot also pass dest=. That raises ValueError: dest supplied twice for positional argument. To change what the user sees in help and usage, set metavar:
import argparse
parser = argparse.ArgumentParser(prog="demo")
parser.add_argument("input_file", metavar="input-file", help="file to read")
args = parser.parse_args(["data.csv"])
print(args.input_file)The help shows input-file, and your code reads args.input_file.
Converting and restricting values
The type and choices keywords work on positionals just as they do on options. A failed conversion is reported against the positional's name:
import argparse
parser = argparse.ArgumentParser(prog="repeat")
parser.add_argument("count", type=int, help="how many times")
parser.add_argument("action", choices=["start", "stop"])
args = parser.parse_args(["3", "start"])
print(args.count, args.action)Calling parse_args(["many", "start"]) prints repeat: error: argument count: invalid int value: 'many' and exits with status 2. An action outside choices is reported as an invalid choice. The exact wording of that message differs between Python versions, so do not match on it in tests.
type=Path only builds a Path object. It does not check that the file exists. If a missing file should be a usage error, write a custom type function that raises argparse.ArgumentTypeError, as the validation chapter shows. If a missing file is a runtime failure, handle it in main, as the example above does.
Making a positional optional with nargs
By default a positional consumes exactly one value. The nargs keyword changes how many it takes, and with that whether it is required. The next chapters cover nargs in full. These are the values to recognize now:
| `nargs` | Values consumed | Required | Type of `args.name` |
|---|---|---|---|
| not set | exactly one | yes | one value |
| `"?"` | zero or one | no | value, or `default` if absent |
| `"*"` | zero or more | no | list (empty if absent) |
| `"+"` | one or more | yes | list |
| an integer `N` | exactly N | yes | list of N values |
A positional only falls back to its default when nargs is "?" or "*". Setting default= on a plain positional has no effect on whether it is required:
import argparse
parser = argparse.ArgumentParser(prog="greet")
parser.add_argument("name", default="world") # still required
parser.add_argument("greeting", nargs="?", default="Hello")
args = parser.parse_args(["Ada"])
print(args.greeting, args.name) # Hello AdaPassing required=True or required=False to a positional raises TypeError: 'required' is an invalid argument for positionals. Use nargs to control it.
Mixing positionals with options
The user may place options before, between or after positionals. These two commands give the same result:
cp-lite --verbose a.txt b.txt
cp-lite a.txt --verbose b.txtThe parser removes option tokens, with the values they consume, and then matches the remaining bare tokens to positionals. This is why an option that takes a value cannot be mistaken for a positional: in --count 2 Ada, the 2 belongs to --count.
Be careful when an option uses nargs="*" or nargs="+". It will take every bare value that follows it, including ones you meant for a positional. In tool --files a b c target, all four values go to --files. Put the positional first, or have the user end the option list with --.
Values that start with a dash
The parser treats a token starting with - as an option. Two cases matter for positionals.
Negative numbers are handled specially. If the parser has no option strings that look like negative numbers, such as -1, then a token like -5 is read as a positional value:
import argparse
parser = argparse.ArgumentParser(prog="double")
parser.add_argument("number", type=int)
print(parser.parse_args(["-5"]).number * 2) # -10Other dash-prefixed values, such as a file named -draft.txt, are rejected as unknown options. The user can type a bare -- to say that everything after it is positional:
import argparse
parser = argparse.ArgumentParser(prog="show")
parser.add_argument("name")
print(parser.parse_args(["--", "-draft.txt"]).name) # -draft.txtThis is the same convention as rm -- -draft.txt. Mention it in your help text if your tool is likely to receive arbitrary file names.
Common mistakes
- Using a positional for something optional. Use an option such as
--outputwhen the value has a sensible default or changes rarely. Reserve positionals for the values the command cannot run without. - Declaring too many positionals. Three or more bare values of the same type are hard for users to remember in order. Switch to options for the extras.
- Assuming
defaultmakes a positional optional. It does not, unless you also setnargs="?"ornargs="*". - Reading a hyphenated name. See the warning above.
- Matching on the full error text. Check the exit code and that the argument name appears in stderr, because the wording changes between Python releases.
Exercise
Given parser.add_argument("name", default="world"), what does parser.parse_args([]) do? Change one line so that it returns Namespace(name='world') instead.
Show answer
It prints a usage line and the error "the following arguments are required: name", then exits with status 2, because a positional without nargs is always required and default is ignored for it. Changing the line to parser.add_argument("name", nargs="?", default="world") makes the positional optional, so parse_args([]) returns Namespace(name='world').
Exercise
A tool declares parser.add_argument("target") and parser.add_argument("--files", nargs="+"). A user runs tool --files a.txt b.txt out/. What happens, and what are two ways to avoid it?
Show answer
The --files option consumes all three values (a.txt, b.txt and out/), so no value is left for target and the parser reports that target is required. The user can write tool out/ --files a.txt b.txt, or end the option list with -- as in tool --files a.txt b.txt -- out/. You could also redesign the tool so that files is a positional with nargs="+" and the destination is an option.