Sub topic 16
When argparse is enough and when to look elsewhere
This chapter assumes you have read the earlier chapters. You should be comfortable with ArgumentParser, options and positional arguments, subcommands, a main(argv) function, and installing a tool through [project.scripts]. The goal is to give you criteria for choosing a library. It does not teach any other library in full.
What argparse gives you
argparse ships with Python. A tool built on it needs no extra packages, installs anywhere Python runs, and keeps working across upgrades because the standard library changes slowly. That matters when you ship a script to servers you do not control, write a build helper, or publish a small package where each dependency is a cost to your users.
It also covers the features most tools need:
- Positional arguments, options, flags, counters and repeated options.
- Type conversion,
choicesand custom validators. - Generated
--helpand usage text. - Subcommands, argument groups and mutually exclusive options.
- Standard error handling: a usage message on stderr and exit status 2.
Because main(argv) takes an argument list and returns an exit code, you can test it with plain pytest, as shown in the testing chapter. Nothing in that approach depends on a third-party test runner.
Where argparse starts to hurt
Each of these costs is real, and none of them is fatal. They are the points where people move to another library.
Boilerplate grows with the tool
Every option is a separate add_argument call, and the function that uses the value is somewhere else. Subcommands need a parser each, a set_defaults(func=...) link and a dispatch step. In a tool with a dozen commands, the parser-building code can become longer than the logic it feeds.
Types are runtime conversions only
type=int converts a string, but your function signature does not say what the parameter is. Type checkers see args.count as Any. Libraries that read type hints can produce the parser from the function signature and keep the two consistent.
One related trap is type=bool. It calls bool("False"), which is True, because any non-empty string is truthy. Use store_true, store_false or argparse.BooleanOptionalAction instead.
Configuration sources are not merged
argparse reads only the command line. If you want the order "command line, then environment variable, then config file, then default", you must write it yourself. You can feed the environment into default=:
import argparse
import os
def build_parser():
parser = argparse.ArgumentParser(prog="fetch")
parser.add_argument(
"--token",
default=os.environ.get("FETCH_TOKEN"),
help="API token (default: $FETCH_TOKEN)",
)
return parser
def main(argv=None):
parser = build_parser()
args = parser.parse_args(argv)
if args.token is None:
parser.error("no token: pass --token or set FETCH_TOKEN")
print("token is set")
return 0
if __name__ == "__main__":
raise SystemExit(main())Do not use required=True here. The parser would reject a missing --token even when the environment variable supplies it. Check after parsing and call parser.error, which prints usage and exits with status 2.
Interactive and terminal features are missing
argparse does not prompt for missing values, hide password input, show progress bars, or colour output on its own. Shell tab completion also needs an add-on package such as argcomplete. Recent Python releases have added some terminal polish, such as coloured help. Check the documentation for the version you target before you rely on it.
Help layout is hard to customise
You can change the formatter class, metavar and epilog. Grouping subcommands under headings or reordering sections quickly leads into formatter internals, which are only partly documented.
The alternatives
| Library | Core idea | Choose it when | Cost |
|---|---|---|---|
| `argparse` | Build a parser object explicitly | You want no dependencies and full control | More boilerplate |
| `click` | Decorators on functions | You need nested command groups, prompts, colour, plugins | Third-party dependency |
| `typer` | Type hints on a function signature | Your functions are already typed and you want little code | Dependency, built on click |
| `fire` | Expose existing objects automatically | Quick internal tools or debugging interfaces | Little control over the interface |
| `docopt` | Write the help text, derive the parser | Rarely a good choice for new code | Largely unmaintained |
| `optparse`, `getopt` | Older standard-library parsers | Only when maintaining old code | Documented as superseded by argparse |
Newer typed libraries such as Cyclopts exist and follow the same signature-driven approach as Typer. Judge any of them by the same criteria below, including how actively they are maintained.
The same greeting tool from the first chapter looks like this in click:
import click
@click.command()
@click.argument("name")
@click.option("-c", "--count", default=1, show_default=True,
help="Number of times to greet.")
@click.option("-v", "--verbose", is_flag=True,
help="Print extra information to stderr.")
def main(name, count, verbose):
if verbose:
click.echo(f"Greeting {name} {count} time(s)", err=True)
for _ in range(count):
click.echo(f"Hello, {name}!")
if __name__ == "__main__":
main()The parser definition and the function have merged. In Typer the options come from the signature:
import typer
def main(name: str, count: int = 1, verbose: bool = False):
if verbose:
typer.echo(f"Greeting {name} {count} time(s)", err=True)
for _ in range(count):
typer.echo(f"Hello, {name}!")
if __name__ == "__main__":
typer.run(main)Typer turns count into --count and verbose into --verbose/--no-verbose. A short alias such as -c needs an explicit typer.Option("--count", "-c") default. Both versions need pip install click or pip install typer first.
Differences that surprise people
- Exit behaviour differs.
argparseraisesSystemExit(2)on a usage error. Click raises its own exception types and exits with status 2 for usage errors, but the testing helpers differ. In click you useclick.testing.CliRunnerinstead of catchingSystemExityourself. - Your
main(argv)pattern changes. A click command is a callable object that readssys.argvitself. You can still pass arguments withmain(args=[...], standalone_mode=False), but the code you wrote aroundmain(argv)and its return value does not carry over unchanged. - Option parsing details differ.
argparseaccepts unambiguous abbreviations of long options by default, so--verbcan match--verbose. Setallow_abbrev=Falseif you do not want that. Check how any replacement library treats abbreviations before you migrate scripts that others call. - Dependencies carry a lifecycle. A third-party parser is one more package to pin, audit and update, and a major version can change behaviour.
A decision procedure
Apply these checks in order:
- Distribution. If the tool must run with only the standard library,
argparsedecides the question. - Size. A tool with one to five options, or a handful of subcommands, does not repay a new dependency.
- Interactivity. Prompts, confirmations and rich terminal output are the clearest reason to pick click.
- Consistency. If the rest of the codebase already uses a library, match it.
- Migration cost. Moving later is mostly mechanical. The parser definition changes while the logic stays. If your logic is in functions that take plain values, not an
argsnamespace, the move is cheap. Keep the logic separate from parsing so the choice stays reversible.
Common mistakes
- Switching libraries to avoid learning argparse. Most complaints come from not using subcommand dispatch,
parentsormain(argv)properly. - Mixing parsing and logic. Passing the whole
argsnamespace deep into the program ties your code toargparse. Pass the specific values instead. - Adding a dependency for colour alone. Check whether the standard library, or a small separate package, covers it.
- Copying help text between libraries. Defaults, metavar names and error messages differ, so re-run your tests after migrating.
Exercise
A teammate wants to rewrite a 40-line internal script that has three options and no subcommands from argparse to click. The script is deployed by copying one file to servers that have only the standard library. Which tool should you keep, and which two criteria from the chapter justify that?
Show answer
Keep argparse. Distribution is the first criterion: the servers have only the standard library, so click would need to be installed on each one. Size is the second: three options and no subcommands give click little to add, so a dependency costs more than it saves.
Exercise
You write parser.add_argument("--token", required=True, default=os.environ.get("API_TOKEN")) so that the environment variable can supply the token. Why does this fail when API_TOKEN is set and --token is missing, and what should you do instead?
Show answer
With required=True, argparse rejects a missing --token before it looks at the default, so the environment value is never used. Remove required=True, keep default=os.environ.get("API_TOKEN"), and after parsing call parser.error(...) if args.token is None.