iter(x) will raise a TypeError if x cannot be repeated, but it checks for "accepts" sets and dictionaries, although it "rejects" other inconsistencies such as None and numbers.
On the other hand, strings (which most applications want to consider "individual elements" rather than sequences) are actually sequences (so any test, unless specifically used for strings, is going to confirm that they are). Thus, such simple checks are often not enough.
In Python 2.6 and above, abstract base classes were introduced, and among other powerful functions, they offer better, systematic support for such category checking.
>>> import collections >>> isinstance([], collections.Sequence) True >>> isinstance((), collections.Sequence) True >>> isinstance(23, collections.Sequence) False >>> isinstance('foo', collections.Sequence) True >>> isinstance({}, collections.Sequence) False >>> isinstance(set(), collections.Sequence) False
You'll notice that strings are still considered a βsequenceβ (since they are), but at least you get dicts and lay aside. If you want to exclude strings from your concept of "being sequences", you can use collections.MutableSequence (but it also excludes tuples that, like strings, are sequences but are not mutable) or do it explicitly:
import collections def issequenceforme(obj): if isinstance(obj, basestring): return False return isinstance(obj, collections.Sequence)
Season to taste and serve hot! -)
Alex Martelli May 30 '10 at 12:46 a.m. 2010-05-30 00:46
source share