I have in Python a list of numbers of any type: int
, float
, complex
, Decimal
and Fraction
. For example:
from decimal import Decimal
from fractions import Fraction
lista_numeros = [2, 2.0, Decimal('2.0'), complex(2,0), Fraction(2,1)]
I would like to know how it is possible to check (in a pythonic way ) that each object is a number without having to check for each of them if it is an instance of any of those possible types.
for numero in lista_numeros:
print("{}: {}".format(numero, isinstance(numero, (int, tuple, complex, Decimal, Fraction))))
In Python there is an abstract class inside the module
numbers
calledNumber
, which represents the root of the entire hierarchy of numbers. Therefore, any object of type number is instantiated from a class that implementsNumber
or some subclass ofNumber
.A solution would be the following:
Resulting:
Note that Python treats the type
bool
as numeric, giving aFalse
the value0
andTrue
a the value1
.SOen entry where much of the information was taken from: https://stackoverflow.com/questions/3441358/python-most-pythonic-way-to-check-if-an-object-is-a-number