Steven C. Howell Steven C. Howell - 1 year ago 105
Python Question

In Python, how would you check if a number is one of the integer types?

In Python, how could you check if the type of a number is an integer without checking each integer type, i.e.,

, or

I thought to try
if int(val) == val
but this does not work when a float is set to an integer value (not type).

In [1]: vals = [3, np.ones(1, dtype=np.int32)[0], np.zeros(1, dtype=np.int64)[0], np.ones(1)[0]]
In [2]: for val in vals:
...: print(type(val))
...: if int(val) == val:
...: print('{} is an int'.format(val))
<class 'int'>
3 is an int
<class 'numpy.int32'>
1 is an int
<class 'numpy.int64'>
0 is an int
<class 'numpy.float64'>
1.0 is an int

I want to filter out the last value, which is a

Answer Source

You can use isinstance with a tuple argument with the types of interest:

>>> [(e, type(e), isinstance(e, (int, np.integer))) for e in vals]
[(3, <type 'int'>, True), 
 (1, <type 'numpy.int32'>, True), 
 (0, <type 'numpy.int64'>, True), 
 (1.0, <type 'numpy.float64'>, False)]

Find only int and int64:

>>> [(e, type(e), isinstance(e, (int, np.int64))) for e in vals]
[(3, <type 'int'>, True), (1, <type 'numpy.int32'>, False), (0, <type 'numpy.int64'>, True), (1.0, <type 'numpy.float64'>, False)]