2

I want to validate a argument based on the value of another argument.

SampleScript.py

    def parse_args():
        parser = argparse.ArgumentParser()
        parser.add_argument('-a', '--arg1', help="Year-Month or Year")
        parser.add_argument('-b', '--arg2', help="Needs Month from argument arg1", action="store_true")
        args = parser.parse_args()
        return args

     def main():
        args = parse_args()

     if __name__ == "__main__":
        main()

Value for arg1 can be in format YYYY or YYYY-MM. However, when the arg2 is set, I want to make sure that the value for arg1 passed is in format 'YYYY-MM' and not 'YYYY'.

i.e when I run python SampleScript.py -a 2011, the program should work fine. when I run python SampleScript.py -a 2011 -b, the program should throw an error since -a is not in YYYY-MM format

Is it possible to do such validation using argparse ?

sophros
  • 14,672
  • 11
  • 46
  • 75
name_masked
  • 9,544
  • 41
  • 118
  • 172
  • Using [`parse_known_args`](http://docs.python.org/dev/library/argparse.html#argparse.ArgumentParser.parse_known_args) is acceptable for your use case? It allows to parse the arguments in more than one step. Otherwise I see no way of achieving what you want *and* letting the user specify `-a` and `-b` without order restrictions. If you impose the user to specify `-b` before `-a` then a custom action would be enough. – Bakuriu Aug 23 '13 at 18:31
  • 2
    In theory you could write a custom `type` or `action` to do this, but if `-a` and `-b` can occur in either order, the logic will be complicated. Doing your own check after `parse_args` will be simpler, since both values are available in the `namespace`. You could still use `parser.error` to produce a standardized error message. – hpaulj Aug 23 '13 at 22:50
  • As presented `-b` does not give any additional information about the users intention. You could just deduce its value from the `-a` value, and never have a conflict. But then this could be part of a larger interface where `-b` has an independent meaning. – hpaulj Aug 23 '13 at 23:00
  • 1
    Does this answer your question? [Cross-argument validation in argparse](https://stackoverflow.com/questions/49000217/cross-argument-validation-in-argparse) – sophros Sep 17 '20 at 09:41

0 Answers0