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

Just think that the code above is brutally ugly. The first part is error-inducing and the other is a check if the value is satisfiable. Error should be raised if at least one of them fails. Is there a way to string these to checks together, so that I don't need to repeat lines? Or just a better and prettier alternative in general? Thanks a lot :)

Snusifer
  • 485
  • 3
  • 17
  • You could change the code in the `except` block to be `ivalue = -1`, that way you only have to write the error text once ¯\\_(ツ)_/¯ – Quinn Sep 19 '19 at 15:13

1 Answers1

1

This will raise a generic Exception if the value is negative inside the try: block, causing it to re-raise the same exception as it would if int(value) threw an exception

def positive_int(value):
    try:
        ivalue = int(value)
        if ivalue <= 0:
            raise Exception
    except:
        raise argparse.ArgumentTypeError("%s is an invalid positive int value" % value)

    return ivalue
Ahndwoo
  • 1,025
  • 4
  • 16