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.

2
  • 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. Commented Apr 21, 2015 at 13:33
  • The canonical duplicate for this question should really be stackoverflow.com/questions/3441358/… Commented May 2, 2022 at 15:51

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.