How can I constrain a value parsed with argparse (for example, restrict an integer to positive values)?

This should be possible utilizing type. You’ll still need to define an actual method that decides this for you:

def check_positive(value):
    ivalue = int(value)
    if ivalue <= 0:
        raise argparse.ArgumentTypeError("%s is an invalid positive int value" % value)
    return ivalue

parser = argparse.ArgumentParser(...)
parser.add_argument('foo', type=check_positive)

This is basically just an adapted example from the perfect_square function in the docs on argparse.

Leave a Comment