Question
Asked By – Arcturus B
I need to test whether a variable is of type int
, or any of np.int*
, np.uint*
, preferably using a single condition (i.e. no or
).
After some tests, I guess that:
isinstance(n, int)
will only matchint
andnp.int32
(ornp.int64
depending on plateform),np.issubdtype(type(n), int)
seems to match allint
andnp.int*
, but doesn’t matchnp.uint*
.
This leads to two questions: will np.issubdtype
match any kind of signed ints? Can determine in a single check whether a number is any kind of signed or unsigned int?
This is about testing for integers, the test should return False
for float-likes.
Now we will see solution for issue: How to determine if a number is any type of int (core or numpy, signed or not)?
Answer
NumPy provides base classes that you can/should use for subtype-checking, rather than the Python types.
Use np.integer
to check for any instance of either signed or unsigned integers.
Use np.signedinteger
and np.unsignedinteger
to check for signed types or unsigned types.
>>> np.issubdtype(np.uint32, np.integer)
True
>>> np.issubdtype(np.uint32, np.signedinteger)
False
>>> np.issubdtype(int, np.integer)
True
>>> np.issubdtype(np.array([1, 2, 3]).dtype, np.integer)
True
All floating or complex number types will return False
when tested.
np.issubdtype(np.uint*, int)
will always be False
because the Python int
is a signed type.
A useful reference showing the relationship between all of these base classes is found in the documentation here.
This question is answered By – Alex Riley
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0