How do you write a custom 'type=' validation function for argparse that raises a properly-formatted error for invalid input?
Short answer
Define a plain function that takes the raw string argument and either returns the converted/validated value or raises argparse.ArgumentTypeError with a descriptive message — argparse catches this specific exception and formats it into the standard, consistent CLI error output…
Advertisement
AModel answer
Define a plain function that takes the raw string argument and either returns the converted/validated value or raises argparse.ArgumentTypeError with a descriptive message — argparse catches this specific exception and formats it into the standard, consistent CLI error output automatically.
def positive_int(value):
ivalue = int(value)
if ivalue <= 0:
raise argparse.ArgumentTypeError(f"{value} is not a positive integer")
return ivalue
parser.add_argument("--count", type=positive_int)
# python script.py --count -5
# error: argument --count: -5 is not a positive integerReal-world example
Validating that a numeric CLI argument (like a batch size or retry count) is strictly positive, with a clear, standard-format error message.
Likely follow-ups
- What's the difference between raising ArgumentTypeError versus a regular ValueError inside a custom type function?
Related topics