pala9323
pala9323

Reputation: 211

How to reject negative numbers as parameters in the Argparse module

I have a time parameter and it can be any number except negatives and zero

parser.add_argument("-t", "--time",
                    default=2, type=int,
                    help="Settings up the resolution time")

How can I use choices option correctly?

Upvotes: 6

Views: 957

Answers (1)

shx2
shx2

Reputation: 64318

You can pass any conversion function as the type= arg of add_argument. Use your own converstion function, which includes the extra checks.

def non_negative_int(x):
    i = int(x)
    if i < 0:
        raise ValueError('Negative values are not allowed')
    return i

parser.add_argument("-t", "--time",
                    default=2, type=non_negative_int,
                    help="Settings up the resolution time")

Upvotes: 7

Related Questions