[Tutor] question re type()

Kent Johnson kent37 at tds.net
Mon Oct 29 12:28:25 CET 2007


Aditya Lal wrote:
> or use types module 
> 
> import types
> 
> if type(n) == types.IntType or type(n) == types.LongType :
>     blah!

A few notes:
- If you look at types.py, you find
IntType = int
LongType = long

and so on for all the built-in types, so there is no need or advantage 
to importing types vs
   if type(n) == int

- Common Python practice is to prefer the least restrictive type check 
possible. For Dick's specific case it doesn't matter, but I generally 
use isinstance() instead of checking for a specific type. The difference 
is that isinstance() is true for subtypes as well as the named type. You 
can also pass a tuple of types to isinstance() so you can say
   if isinstance(n, (int, long))

Kent




More information about the Tutor mailing list