How to use isinstance to test all possible integer types

Viewed 473

When working with integers there are multiple types available (e.g. int, numpy.int8, numpy.int16, etc.). If I write a generic function that requires one variable to be an integer how can I test the type against all possible "integer" types within Python/numpy? The same can be asked about floats. I initially thought this

isinstance(np.int64(5), int)

would/should work, but it doesn't.

Is there a way I can test an integer variable for all available integer types?

2 Answers

You can use numbers.Integral and numbers.Real respectively:

from numbers import Integral, Real

isinstance(x, Integral)
isinstance(x, Real)

In Python there is only a single int type. If you want to test all integer types in numpy, plus the built-in int type, you can use:

isinstance(x, (int, np.integer))

Where np.integer is an abstract base class of all scalar numpy integer types. Similarly for float,

isinstance(x, (float, np.floating))
Related