[Tutor] checking if a variable is an integer?

Steven D'Aprano steve at pearwood.info
Wed Jun 1 00:13:28 CEST 2011


Peter Lavelle wrote:
> I think you could also use the type() function. See example below:
> 
> if type(yourvar) == int:
>     #Do stuff here if it is an integer


You can do that, but that will miss out on subclasses of int. It is 
better to use isinstance(yourvar, int) which will accept an int, or a 
subclass of int.

In Python 2.x (but not 3) you should also test for long:

isinstance(yourvar, (int, long))


But for some purposes, it might be even better to use duck typing ("if 
it quacks like a duck, swims like a duck, and looks like a duck, it 
probably is a duck"):


def is_int_value(obj):
     try:
         return int(x) == x
     except (TypeError, ValueError):
         return False

This will accept as an integer values like Fraction(5, 1), 
Decimal("23.0") or 42.0, as well as the usual ints 5, 23 or 42 ...



-- 
Steven



More information about the Tutor mailing list