Posted By: Anonymous
In python, what’s the best way to test if a variable contains a list or a tuple? (ie. a collection)
isinstance() as evil as suggested here? http://www.canonical.org/~kragen/isinstance/
Update: the most common reason I want to distinguish a list from a string is when I have some indefinitely deep nested tree / data-structure of lists of lists of lists of strings etc. which I’m exploring with a recursive algorithm and I need to know when I’ve hit the “leaf” nodes.
Go ahead and use
isinstance if you need it. It is somewhat evil, as it excludes custom sequences, iterators, and other things that you might actually need. However, sometimes you need to behave differently if someone, for instance, passes a string. My preference there would be to explicitly check for
unicode like so:
import types isinstance(var, types.StringTypes)
N.B. Don’t mistake
types.StringTypes. The latter incorporates
types module is considered by many to be obsolete in favor of just checking directly against the object’s type, so if you’d rather not use the above, you can alternatively check explicitly against
unicode, like this:
isinstance(var, (str, unicode)):
Better still is:
After either of these, you can fall back to behaving as if you’re getting a normal sequence, letting non-sequences raise appropriate exceptions.
See the thing that’s “evil” about type checking is not that you might want to behave differently for a certain type of object, it’s that you artificially restrict your function from doing the right thing with unexpected object types that would otherwise do the right thing. If you have a final fallback that is not type-checked, you remove this restriction. It should be noted that too much type checking is a code smell that indicates that you might want to do some refactoring, but that doesn’t necessarily mean you should avoid it from the getgo.