1

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.

Vivian De Smedt
  • 1,019
  • 2
  • 16
  • 26
  • Sometimes you _do_ need such explicit tests, but it's nice to avoid them when possible so that you get the full benefits of [duck typing](http://en.wikipedia.org/wiki/Duck_typing). – PM 2Ring Apr 21 '15 at 13:33
  • The canonical duplicate for this question should really be https://stackoverflow.com/questions/3441358/what-is-the-most-pythonic-way-to-check-if-an-object-is-a-number – joanis May 02 '22 at 15:51

2 Answers2

10

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.

vaultah
  • 44,105
  • 12
  • 114
  • 143
  • 2
    And of course `isinstance(o, numbers.Number)` is generally superior to `isinstance(o, (int, long, float, complex))` since it means that any object which claims to be some kind of number will pass the test. – PM 2Ring Apr 21 '15 at 13:34
3

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))
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140