I am running in this multiple times now and never found a satisfying solution.
I want to check: Is variable some_var of a number type?
More specific for me: Can it be compared to another number? (e.g. a string should fail)
Numpy makes this somehow difficult since:
some_var = np.int32(123)
isinstance(some_var, int)
>>> False
Possible Solutions
numpy solutions: np.issubtype, comparison to np.number, np.isscalar
I found np.issubtype as workaround, but this will fail for non-numpy types:
some_var = 123
np.issubdtype(some_var.dtype, np.number)
>>> AttributeError: 'int' object has no attribute 'dtype'
np.number can be used for comparison, but also fails for non-numpy types
isinstance(1, np.number)
>>> False
np.isscalar() works fine, but also allows strings:
np.isscalar('test')
>>>True
numbers module
There is the comparison with the numbers module. Which seems to work convenient, but needs an extra import. So far probably the best solution.
from numbers import Integral
isinstance(some_var, Integral)
>>> True
Manual testing
The clearest way of course would be a manual test.
isinstance(some_var, (int, float, np.int32, np.int64, np.float32, np.float64))
>>> True
My Questions
Am I missing a way?
What would be the most recommended?