How can I check if a Python variable is an integer, including numpy.int*?

I would like to use an abstract way of checking whether a variable is an integer. I know I can do:

>>> a = 1
>>> isinstance(a, int)

True

However, this does not work for some special types of integers, e.g.:

>>> import numpy as np
>>> b = np.int64(1)
>>> isinstance(b, int)

False

I know I can also do:

>>> isinstance(b, np.integer)

True

But unfortunately, np.integer is not “abstract” enough to match an ordinary int:

>>> isinstance(a, np.integer)

False

What can I do to check and conclude that both a and b are “integers”, preferably in a way that also matches other “integer-in-spirit” special data types that other packages than NumPy might bring to the party?

  • 2

    isinstance(x, (np.integer, int)) Is that what you’re looking for?

    – 

>>>
>>> import numbers
>>> import numpy as np
>>>
>>>
>>> def is_integer(value):
...   return isinstance(value, numbers.Integral)
...
>>> a = 1
>>> print(is_integer(a))
True
>>>
>>> b = np.int64(1)
>>>
>>> print(is_integer(b))
True
>>> c = np.int32(1)
>>> print(is_integer(c))
True
>>> d = 1.5
>>> print(is_integer(d))
False
>>>

To check whether a variable is an integer or any integer-like object, you can use the numbers module in Python, which provides a hierarchy of abstract base classes for numeric types. The Integral abstract base class in the numbers module represents integer types.

Leave a Comment