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
