Skip to content

Add parameter validator to argparse.ArgumentParser.add_argument #154755

Description

@bjhend

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions