Use Number
from the numbers
module to test isinstance(n, Number)
(available since 2.6).
isinstance(n, numbers.Number)
Here it is in action with various kinds of numbers and one non-number:
>>> from numbers import Number
... from decimal import Decimal
... from fractions import Fraction
... for n in [2, 2.0, Decimal('2.0'), complex(2,0), Fraction(2,1), '2']:
... print '%15s %s' % (n.__repr__(), isinstance(n, Number))
2 True
2.0 True
Decimal('2.0') True
(2+0j) True
Fraction(2, 1) True
'2' False
This is, of course, contrary to duck typing. If you are more concerned about how an object acts rather than what it is, perform your operations as if you have a number and use exceptions to tell you otherwise.
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)
That's not really how python works. Just use it like you would a number, and if someone passes you something that's not a number, fail. It's the programmer's responsibility to pass in the correct types.
Sure you can use isinstance
, but be aware that this is not how Python works. Python is a duck typed language. You should not explicitly check your types. A TypeError
will be raised if the incorrect type was passed.
So just assume it is an int
. Don't bother checking.
Source: Stackoverflow.com