Search code examples
pythonpython-3.xnumpytypesisinstance

How to use isinstance to test all possible integer types


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?


Solution

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

    from numbers import Integral, Real
    
    isinstance(x, Integral)
    isinstance(x, Real)