What is the best way to determine if a Python object is numeric? I'm using the following test
type(o) in [int, long, float, complex]
But I wonder if there is another way.
What is the best way to determine if a Python object is numeric? I'm using the following test
type(o) in [int, long, float, complex]
But I wonder if there is another way.
The preferred approach is to use numbers.Number
, which is
The root of the numeric hierarchy. If you just want to check if an argument x is a number, without caring what kind, use isinstance(x, Number)
as shown below
In [1]: import numbers
In [2]: isinstance(1, numbers.Number)
Out[2]: True
In [3]: isinstance(1.0, numbers.Number)
Out[3]: True
In [4]: isinstance(1j, numbers.Number)
Out[4]: True
Also, type(o) in [int, long, float, complex]
can be rewritten as
isinstance(o, (int, long, float, complex))
to make it more robust, as in able to detect subclasses of int, long, float and complex.
Try the isinstance
function.
Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof
Sample Usage
isinstance(o, (int, long, float, complex))