if iter(iterator) is iterator
Chris Angelico
rosuav at gmail.com
Sun Nov 13 19:59:22 EST 2016
On Mon, Nov 14, 2016 at 11:40 AM, Steve D'Aprano
<steve+python at pearwood.info> wrote:
> def isiterable(obj):
> """Return True if obj is an iterable, and False otherwise.
>
> Iterable objects can be iterated over, and they provide either
> an __iter__ method or a __getitem__ method.
>
> Iteration over an object tries calling the object's __iter__
> method (if any), then repeatedly calls __next__ on the result
> until a StopIteration exception is raised (the Iterator
> Protocol). Otherwise, it tries calling __getitem__ with
> arguments 0, 1, 2, 3 ... until an IndexError exception is
> raised (the Sequence Protocol).
>
> """
> T = type(obj)
> return hasattr(T, '__iter__') or hasattr(T, '__getitem__')
Any particular reason to write it that way, rather than:
def isiterable(obj):
try:
iter(obj)
return True
except TypeError:
return False
?
ChrisA
More information about the Python-list
mailing list