Feature or enhancement
Proposal:
I propose to add an optional parameter validator to argparse.ArgumentParser.add_argument. It should accept a callable with one argument of the type of the added parameter and return a boolean. If present the following should happen:
- On argument parsing the usual type conversion and value checks should be executed
- Then the
validator callable is called with the parsed and type-converted argument
- If the result is
True nothing happens and parsing is resumed
- If the result is
False the value is rejected as invalid by raising an argparse.ArgumentError explaining the failed validation
In addition, if a default value is given it should be validated similarly by add_argument.
Maybe it would be useful to add a special exception ArgumentValidationError derived from ArgumentError that also receives the invalid parsed value.
Example
import argparse
def validate(val: int):
return (val >= 10) and (val <= 100)
parser = argparse.ArgumentParser()
parser.add_argument('--foo', type=int, validator=validate, help="Set to value between 10 and 100")
args = parser.parse_args()
print(args.foo)
Now, if the program is called with --foo 5 an exception is raised pointing out the validation error.
Has this already been discussed elsewhere?
No response given
Links to previous discussion of this feature:
No response
Feature or enhancement
Proposal:
I propose to add an optional parameter
validatortoargparse.ArgumentParser.add_argument. It should accept a callable with one argument of the type of the added parameter and return a boolean. If present the following should happen:validatorcallable is called with the parsed and type-converted argumentTruenothing happens and parsing is resumedFalsethe value is rejected as invalid by raising anargparse.ArgumentErrorexplaining the failed validationIn addition, if a default value is given it should be validated similarly by
add_argument.Maybe it would be useful to add a special exception
ArgumentValidationErrorderived fromArgumentErrorthat also receives the invalid parsed value.Example
Now, if the program is called with
--foo 5an exception is raised pointing out the validation error.Has this already been discussed elsewhere?
No response given
Links to previous discussion of this feature:
No response