liveBook · Manning

Parser.error()

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

parser.error() is an argparse parser method that reports a command-line parsing error, displays usage information, and terminates the program with a failure status.

parser.error() is an argparse parser method for handling command-line arguments that pass basic parsing but fail a rule your program must check itself. It prints short usage information, reports a specific error, stops execution, and exits with a nonzero status. section 9.3.2

Keep validation in the argument-parsing function so main() receives validated data. argparse can enforce types such as int or float; parser.error() handles constraints such as positive numbers or allowed ranges. section 9.1.1 section 10.3

Rejecting an invalid range

args = parser.parse_args() if args.adjectives < 1: parser.error(f'--adjectives "{args.adjectives}" must be > 0') return args $ ./abuse.py -a -4 usage: abuse.py [-h] [-a adjectives] [-n insults] [-s seed] abuse.py: error: --adjectives "-4" must be > 0 section 9.1.1

Use parser.error() when:

  • An argument has a valid type but an invalid value, such as a negative count or a percentage outside 0–1. section 10.1
  • The user needs both a concise usage statement and an actionable explanation of the problem. section 9.3.2
  • Tests need to verify failure status and diagnostic output. section 9.1.1
$ ./abuse.py -a -4
usage: abuse.py [-h] [-a adjectives] [-n insults] [-s seed]
abuse.py: error: --adjectives "-4" must be > 0
$ ./abuse.py -n -4
usage: abuse.py [-h] [-a adjectives] [-n insults] [-s seed]
abuse.py: error: --number "-4" must be > 0

Compare the usage line and custom diagnostics produced for invalid adjective and insult counts. section 9.1.1

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Explains output, termination, and placement in get_args(), but does not explore argparse internals.
Examples
Demonstrates invalid counts, mutation ranges, song-day limits, terminal diagnostics, and tests asserting nonzero status.
What it assumes
Assumes argparse parsing and typed arguments, while teaching manual checks for constraints argparse cannot easily express.
What you can do after
Apply it via argparse to stop programs cleanly when parsed arguments violate application-specific rules.
How it connects
Connects argparse with command-line argument validation, usage messages, exit status, and automated tests.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.