On Mon, Nov 14, 2016 at 11:40 AM, Steve D'Aprano
<steve+pyt...@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
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to