I can check for a next() method, but is that enough? Is there an idiomatic way?
I can check for a next() method, but is that enough? Is there an
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In Python 2.6 or better, the designed-in idiom for such behavioral checks is a “membership check” with the abstract base class in the
collectionsmodule of the standard library:Indeed, this kind of checks is the prime design reason for the new abstract base classes (a second important one is to provide “mixin functionality” in some cases, which is why they’re ABCs rather than just interfaces — but that doesn’t apply to
collections.Iterable, it exists strictly to allow such checks withisinstanceorissubclass). ABCs allow classes that don’t actually inherit from them to be “registered” as subclasses anyway, so that such classes can be “subclasses” of the ABC for such checks; and, they can internally perform all needed checks for special methods (__iter__in this case), so you don’t have to.If you’re stuck with older releases of Python, “it’s better to ask forgiveness than permission”:
but that’s not as fast and concise as the new approach.
Note that for this special case you’ll often want to special-case strings (which are iterable but most application contexts want to treat as “scalars” anyway). Whatever approach you’re using to check iterableness, if you need such special casing just prepend a check for
isinstance(x, basestring)— for example:Edit: as pointed out in a comment, the question focuses on whether an object is an iter***ator*** rather than whether it’s iter***able*** (all iterators are iterable, but not vice versa — not all iterables are iterators).
isinstance(x, collections.Iterator)is the perfectly analogous way to check for that condition specifically.