I found some old Python code that was doing something like:
if type(var) is type(1):
...
As expected, pep8 complains about this recommending usage of isinstance().
Now, the problem is that the numbers module was added in Python 2.6 and I need to write code that works with Python 2.5+
So if isinstance(var, Numbers.number) is not a solution.
Which would be the proper solution in this case?
In Python 2, you can use the
typesmodule:Note the use of a tuple to test against multiple types.
Under the hood,
IntTypeis just an alias forint, etc.:The
complextype requires that your python was compiled with support for complex numbers; if you want to guard for this use a try/except block:or if you just use the types directly:
In Python 3
typesno longer has any standard type aliases,complexis always enabled and there is no longer alongvsintdifference, so in Python 3 always use:Last but not least, you can use the
numbers.Numbersabstract base type (new in Python 2.6) to also support custom numeric types that don’t derive directly from the above types:This check also returns
Truefordecimal.Decimal()andfractions.Fraction()objects.This module does make the assumption that the
complextype is enabled; you’ll get an import error if it is not.