Pass --verbose False to a script whose author used type=bool, and the script runs verbose. Python reads any non-empty string as true, so the word “False” counts as yes. Python’s own documentation warns against that exact pattern, and it is one of several places where argparse, the standard library’s command-line parser, does something reasonable that still surprises people. Every example below was run on Python 3.13 and 3.14, with the real output shown, so the behavior is what the interpreter actually does rather than what the code looks like it should do.
A complete script in fifteen lines
What argparse is for
The official argparse documentation describes the job in plain terms: the program declares the arguments it needs, argparse works out how to parse them from sys.argv, generates help and usage messages automatically, and issues errors when users give invalid arguments. A script that reads sys.argv[1] by hand gets none of that.
The test script
A small backup command covers most of what real scripts need:
import argparse
parser = argparse.ArgumentParser(prog="backup", description="Copy a folder somewhere safe.")
parser.add_argument("source", help="folder to back up")
parser.add_argument("dest", nargs="?", default="/mnt/backup", help="where to put it")
parser.add_argument("-n", "--keep", type=int, default=7, help="snapshots to keep")
parser.add_argument("-v", "--verbose", action="count", default=0)
parser.add_argument("--exclude", action="append", default=[])
parser.add_argument("--compress", choices=["none", "gzip", "zstd"], default="zstd")
parser.add_argument("--dry-run", action="store_true")
parser.add_argument("--checksum", action=argparse.BooleanOptionalAction, default=True)
args = parser.parse_args()
print(args)Run with only a source folder, it filled in every default:
$ python3 backup.py ~/photos
Namespace(source='/root/photos', dest='/mnt/backup', keep=7, verbose=0, exclude=[], compress='zstd', dry_run=False, checksum=True)
The --dry-run flag became args.dry_run. Dashes inside option names turn into underscores in the attribute name, which is why the code reads args.dry_run and not args.dry-run.
Everything at once
$ python3 backup.py ~/photos /media/usb -vv --exclude '*.tmp' --exclude cache --keep 30 --no-checksum
Namespace(source='/root/photos', dest='/media/usb', keep=30, verbose=2, exclude=['*.tmp', 'cache'], compress='zstd', dry_run=False, checksum=False)
The second positional argument filled dest. The doubled -vv counted to 2. Each --exclude added to a list. And --no-checksum existed without anyone writing it.

Positional vs optional, and the actions that matter
Positional arguments are required by position
source has no dashes, so it is positional and required. dest uses nargs="?", which the documentation describes as consuming one argument if possible and falling back to the default if none is present. The two other common settings: nargs="*" gathers any number of arguments into a list, and nargs="+" does the same but errors out if there isn’t at least one.
Options are meant to be optional
Anything starting with a dash is an option. argparse does let a script set required=True on one, but the documentation is blunt about it: required options are generally considered bad form, because users expect options to be optional. If a value is truly mandatory, a positional argument says so more honestly.
The actions worth knowing
The action= setting decides what happens when an option appears. The documented list includes:
| Action | What it stores | Typical use |
|---|---|---|
store (default) |
The value given | --keep 30 |
store_true / store_false |
True or False, no value needed |
--dry-run |
count |
How many times the flag appeared | -v, -vv, -vvv |
append |
A list, one item per use | --exclude a --exclude b |
extend |
A list, several items per use | --files a b c with nargs="+" |
BooleanOptionalAction |
True or False from --x / --no-x |
--checksum / --no-checksum |
The documentation describes count as useful for increasing verbosity levels, which is exactly how the script used it. BooleanOptionalAction arrived in Python 3.9; adding --checksum creates both the positive and the --no- form automatically.
Types, choices, and the help screen
Bad input stops at the door
The type=int on --keep converted the string to a number, and refused anything that wasn’t one:
$ python3 backup.py ~/photos --keep thirty
usage: backup [-h] [-n KEEP] [-v] [--exclude EXCLUDE]
[--compress {none,gzip,zstd}] [--dry-run]
[--checksum | --no-checksum]
source [dest]
backup: error: argument -n/--keep: invalid int value: 'thirty'
[exit 2]
According to the documentation, if the type function raises ValueError, TypeError or ArgumentTypeError, argparse catches it and prints a formatted error. Any Python function that takes a string works as a type, so type=pathlib.Path or a custom validator is a one-word change.
choices restricts a value to a fixed set, and the error lists the options:
$ python3 backup.py ~/photos --compress lz4
backup: error: argument --compress: invalid choice: 'lz4' (choose from 'none', 'gzip', 'zstd')
[exit 2]
The documentation notes that choices are checked after type conversion, so a list of integers in choices needs type=int alongside it.
Exit code 2 is the convention
Every error above ended with exit status 2. The documentation describes that as the normal behavior: print a message to standard error and exit with status 2. Shell scripts that call a Python tool can test for it. A program that wants to handle errors itself can pass exit_on_error=False (added in Python 3.9) and catch argparse.ArgumentError instead.
The free help screen
--help printed this without a line of extra code:
positional arguments:
source folder to back up
dest where to put it
options:
-h, --help show this help message and exit
-n, --keep KEEP snapshots to keep
-v, --verbose
--exclude EXCLUDE
--compress {none,gzip,zstd}
--dry-run
--checksum, --no-checksum
The options without help= text show up bare. Writing a few words for each costs nothing and turns --help into the script’s manual.

Subcommands and mutually exclusive flags
Subcommands, git-style
Tools like git split their work into subcommands, each with its own options. argparse handles this with add_subparsers(), which the documentation describes as returning an object whose add_parser() method creates a full parser for each command:
parser = argparse.ArgumentParser(prog="notes")
sub = parser.add_subparsers(dest="command", required=True)
add = sub.add_parser("add")
add.add_argument("text")
lst = sub.add_parser("list")
lst.add_argument("--limit", type=int, default=10)The results:
['add', 'buy milk'] -> Namespace(command='add', text='buy milk')
['list', '--limit', '3'] -> Namespace(command='list', limit=3)
[] -> notes: error: the following arguments are required: command
dest="command" records which subcommand ran, and required=True stops the script from running with no command at all. Without dest, the program has no clean way to tell which subcommand the user picked.
Flags that can’t appear together
A mutually exclusive group lets argparse enforce “one or the other”:
group = parser.add_mutually_exclusive_group()
group.add_argument("--quiet", action="store_true")
group.add_argument("--loud", action="store_true")Passing both produced demo: error: argument --loud: not allowed with argument --quiet and exit status 2. The usage line also showed [--quiet | --loud], so the rule appears in the help without extra work.
The surprises
type=bool does not do what it says
The test that opened this article:
parser.add_argument("--verbose", type=bool)
parser.parse_args(["--verbose", "False"])
# Namespace(verbose=True)The documentation explains it: bool() turns empty strings into False and every other string into True, so “False” becomes True. It recommends action="store_true" or BooleanOptionalAction instead.
Abbreviations work until they don’t
The backup script never defined --dry, yet python3 backup.py ~/photos --dry set dry_run=True. argparse accepts any unambiguous prefix of a long option by default. Adding a second option, --dryer, broke it:
amb: error: ambiguous option: --dry could match --dry-run, --dryer
That matters for scripts other people call. A wrapper that passes --dry works today and fails the day someone adds a similar option. The documentation offers allow_abbrev=False to turn prefix matching off.
Negative numbers and the double dash
A calculator script with one positional number accepted -5 as a value, not an option. The documentation spells out the rule: a positional argument may begin with a dash only if it looks like a negative number and the parser has no options that look like negative numbers. For values that start with a dash and aren’t numbers, a bare -- tells argparse that everything after it is positional, so -- -5 and -- -filename both pass through.
Defaults that are strings get converted
parser.add_argument("--n", type=int, default="5") produced n=5, an integer. The documentation notes that the type converter is applied to a default only when the default is a string. A default of 5 (no quotes) is left alone; a default of "5" goes through int().

Partial parsing and newer features
parse_known_args for wrappers
A script that passes most of its arguments to another program can parse only the ones it knows. In the test, a parser that defined only --port returned:
(Namespace(port=8080), ['--workers', '4', 'app.py'])
parse_known_args() returns a tuple: the parsed namespace and a list of everything it didn’t recognize, ready to hand on. Plain parse_args() would have stopped with an “unrecognized arguments” error.
Typo suggestions in Python 3.14
Python 3.14 added a suggest_on_error option to the parser. With it switched on, a mistyped choice produced:
backup: error: argument --compress: invalid choice: 'gzp', maybe you meant 'gzip'? (choose from 'none', 'gzip', 'zstd')
On 3.14 it is off unless set, and Python 3.13 rejects the keyword outright with a TypeError, so scripts that must run on older interpreters should leave it out. Python 3.14 also added a color option for colored help output.
When argparse is the right tool
argparse ships with every Python install, so a script that uses it needs no extra packages. Third-party libraries such as Click and Typer build command-line interfaces from decorators or type hints, and some people prefer them for large tools. For a script that needs a few options, a help screen and sensible errors, the fifteen-line version above does the job, as long as nobody writes type=bool.
Sources
- argparse: Parser for command-line options, arguments and subcommands, Python documentation: https://docs.python.org/3/library/argparse.html
