[Tutor] validation

Terry Carroll carroll at tjc.com
Mon Aug 27 21:07:37 CEST 2007


On Mon, 27 Aug 2007, Kent Johnson wrote:

> For the built-in types, since Python 2.2 the familiar name (int, str, 
> float, list, dict, set) *is* the type and you can compare to that 
> directly, e.g.:
> 
> In [13]: type(3)==int
> Out[13]: True
> In [14]: type([]) == list
> Out[14]: True

That is so cool.  I never knew that.

Last night, I coded a routine that could accept either 1) a string, or 2) 
a list or tuple of such strings or 3) a list or tuple of lists or tuples 
of such strings.

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

Then I used 

  if isListOrTuple(param):
     stuff
  else:
     other stuff

How much cleanar it would have been to just write:

  if type(param) in [list, tuple]:
     stuff
  else:
     other stuff

Thanks, Kent.



More information about the Tutor mailing list