Reputation: 6263
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?
Upvotes: 2
Views: 1668
Reputation: 36249
You can use numbers.Integral
and numbers.Real
respectively:
from numbers import Integral, Real
isinstance(x, Integral)
isinstance(x, Real)
Upvotes: 6
Reputation: 95948
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))
Upvotes: 5