Thoughts on using isinstance

Diez B. Roggisch deets at nospam.web.de
Wed Jan 24 12:59:46 EST 2007


abcd wrote:

> good point.  is there place that documents what methods/attrs I should
> check for on an object?  for example, if its a list that I expect I
> should verify the object that is passed in has a ??? function? etc.

Don't check, try. Catch a possible exception, and continue with another type
assumption. The only thing one often checks is for basestring, as
basestring supports iteration, but more than often isn't supposed to be
iterated over. 

Small example to gather all strings out of a tree of objects (untested):

def foo(arg):
   # string case
   if isinstance(arg, basestring):
      return [arg]
   # dict-like
   try:
      res = []
      for value in arg.itervalues():
          res.extend(foo(value))
      return res
   except AttributeError:
      pass
   # generally iterables
   res = []
   for value in arg:
       res.extend(foo(value))
   return res

Diez



More information about the Python-list mailing list