Positional arguments vs options

argparse · Essentials · 8 min

Choosing the right kind of argument is the core of a pleasant command-line interface.

argparse decides the kind of argument from its name.

Positional arguments have plain names ("src"). They are identified by position, are required by default, and appear in the Namespace under that name.

Optional arguments (options) start with - or --. You can give a short and a long form: add_argument("-o", "--output"). They may appear in any order and are optional by default; if absent, their value is None unless you set a default. The attribute name comes from the first long name, with dashes turned into underscores: --dry-run becomes args.dry_run. Use dest= to choose another name.

Options take a value either as the next word (-o out.txt, --output out.txt) or attached (--output=out.txt, -oout.txt).

Conventions that users expect:

  • positionals for the main inputs (files, names),
  • options for modifiers with sensible defaults,
  • long names that read like English, short names only for frequently used options.

You can make an option mandatory with required=True, but the docs consider that bad form: if it is always needed, it is probably a positional.

Example

import argparse

p = argparse.ArgumentParser(prog="copy")
p.add_argument("src")
p.add_argument("dst")
p.add_argument("-o", "--output-format")
p.add_argument("--dry-run", action="store_true")

print(p.parse_args(["a.txt", "b.txt"]))
# Namespace(src='a.txt', dst='b.txt', output_format=None, dry_run=False)
a = p.parse_args(["--output-format=json", "a.txt", "--dry-run", "b.txt"])
print(a.output_format, a.src, a.dst, a.dry_run)   # json a.txt b.txt True
print(p.parse_args(["-ojson", "x", "y"]).output_format)  # json

Remember

  • Plain names are positional and required; dashed names are optional
  • --long-name becomes args.long_name
  • Option values can follow as the next word or with =

Watch out for

  • Expecting args.output-format to work; the attribute uses underscores: args.output_format.

Check yourself

  1. add_argument('--max-retries') stores its value under which attribute?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.python.org/3/library/argparse.html#name-or-flags