How can I check if my python object is a number?


In Java the numeric types all descend from Number so I would use

(x instanceof Number).

What is the python equivalent?

11/8/2015 9:55:57 AM

Accepted Answer

In more recent Python versions (2.6+; in older versions you're pretty much limited to checking for a few hardcoded types), the correct way is to test if your variable is an instance of numbers.Number:

>>> import numbers
>>> import decimal
>>> [isinstance(x, numbers.Number) for x in (0, 0.0, 0j, decimal.Decimal(0))]
[True, True, True, True]

This uses ABCs and will work for all build-in number-like classes, and also for all third-party classes if they are worth their salt (registered as subclasses of the Number ABC). However, in many cases you shouldn't worry about checking typed manually - Python is duck-typed and mixing somewhat compatible types usually works, yet it will barf an error message when some operation doesn't make sense (4 - "1"), so manually checking this is rarely really needed. It's just bonus, you can add it when finishing this module to avoid pestering others with implementation details.

8/11/2019 3:00:18 PM

Python 2: isinstance(x, (int, long, float, complex)) and not isinstance(x, bool)

Python 3: isinstance(x, (int, float, complex)) and not isinstance(x, bool)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow