Python: Test if an argument is an integer

str.isdigit() can be used to test if a string is comprised solely of numbers.


If you're running Python 2.7, try importing argparse. Python 3.2 will also use it, and it is the new preferred way to parse arguments.

This sample code from the Python documentation page takes in a list of ints and finds either the max or the sum of the numbers passed.

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

Python way is to try and fail if the input does not support operation like

try:
   sys.argv = sys.argv[:1]+map(int,sys.argv[1:])
except:
   print 'Incorrect integers', sys.argv[1:]

More generally, you can use isinstance to see if something is an instance of a class.

Obviously, in the case of script arguments, everything is a string, but if you are receiving arguments to a function/method and want to check them, you can use:

def foo(bar):
    if not isinstance(bar, int):
        bar = int(bar)
    # continue processing...

You can also pass a tuple of classes to isinstance:

isinstance(bar, (int, float, decimal.Decimal))