"Steven Bethard" wrote: > John Reese wrote: > > I now do: > > > > if isinstance(x, list): > > > > It is my understanding that this is what people do nowadays. > > I wouldn't go that far. I don't have an isinstance check for lists > anywhere in my entire codebase. Why do you think you need to check to > see if something is of type list? Why don't you just use it as needed, > and find out, e.g.: > > try: > itr = iter(x) > except TypeError: > # do whatever you need to do if it's not iterable > else: > # do whatever you need to do if it *is* iterable
A class of cases I've found necessary to do explicit type checking is when a different action is taken for different types, but where duck typing can't distinguish between them. For example, a function that returns a string representation of an S-expression, represented as a list of nested lists: def s_expr(obj): if isinstance(obj, list): return "(%s)" % ' '.join(map(s_expr,obj)) else: return str(obj) >>> s_expr([1, [2,3], [4,5], "foo"]) >>> '(1 (2 3) (4 5) foo)' Here duck typing doesn't help because the function should take the if branch only for lists and not other iterables (e.g. strings). George -- http://mail.python.org/mailman/listinfo/python-list