If any command line arguments need further restrictions than a simple "type" restriction (for example if they need to be a non-negative integer), it would be good to add these restrictions directly in the function that passes arguments.
Why is this useful
This would be useful so the program will "fail fast" right within the parsing function if the user passes any option values that don't meet the requirements, without waiting for another function to perform the sanity check later in the program.
How can it be implemented
The argparse.add_argumenttype argument can be set to any callable. This could be set to a function that checks the specific restriction.
For example, to restrict a value to be a non-negative integer, the following function can be implemented:
def check_non_negative(value: str) -> int:
msg = "Value must be a non-negative integer."
try:
ivalue = int(value)
except ValueError:
raise argparse.ArgumentTypeError(msg)
if ivalue < 0:
raise argparse.ArgumentTypeError(msg)
return ivalue
And then, the argparse.ArgumentParser.add_argument line could be something like:
Description
If any command line arguments need further restrictions than a simple "type" restriction (for example if they need to be a non-negative integer), it would be good to add these restrictions directly in the function that passes arguments.
Why is this useful
This would be useful so the program will "fail fast" right within the parsing function if the user passes any option values that don't meet the requirements, without waiting for another function to perform the sanity check later in the program.
How can it be implemented
The
argparse.add_argument
type argument can be set to any callable. This could be set to a function that checks the specific restriction. For example, to restrict a value to be a non-negative integer, the following function can be implemented:And then, the
argparse.ArgumentParser.add_argument
line could be something like: