[Tutor] validation

Kent Johnson kent37 at tds.net
Mon Aug 27 21:18:39 CEST 2007


Terry Carroll wrote:

> I ended up writing a short isListOrTuple function that went something 
> like this:
> 
> def isListOrTuple(thing):
>   result = False
>   if isinstance(thing, list): result = True
>   if isinstance(thing, tuple): result = True
>   return result

isinstance can take a tuple of types as its second argument so this 
could be written

def isListOrTuple(thing):
   return isinstance(thing, (list, tuple))

> How much cleanar it would have been to just write:
> 
>   if type(param) in [list, tuple]:
>      stuff
>   else:
>      other stuff

Note that
   isinstance(thing, (list, tuple))

and
   type(thing) in [list, tuple]

are not equivalent. The first will be true for objects whose type is a 
subclass of list and tuple while the second will not.

In [2]: class Foo(list): pass
    ...:
In [3]: f=Foo()
In [4]: type(f)
Out[4]: <class '__main__.Foo'>
In [5]: type(f) in [list, tuple]
Out[5]: False
In [6]: isinstance(f, list)
Out[6]: True

Kent


More information about the Tutor mailing list