if iter(iterator) is iterator

eryk sun eryksun at gmail.com
Mon Nov 14 01:43:34 EST 2016


On Mon, Nov 14, 2016 at 6:25 AM, Serhiy Storchaka <storchaka at gmail.com> wrote:
> On 14.11.16 02:40, Steve D'Aprano wrote:
>>
>> I'm surprised that the inspect module doesn't appear to have isiterable
>> and isiterator functions. Here's my first attempt at both:
>
> Just use isinstance() with collections ABC classes.

Except objects that use the legacy __getitem__ iterator aren't
instances of collections.Iterable:

    class C:
        def __getitem__(self, index):
            return index

    o = C()

    >>> isinstance(o, collections.Iterable)
    False
    >>> it = iter(o)
    >>> type(it)
    <class 'iterator'>
    >>> next(it), next(it), next(it)
    (0, 1, 2)



More information about the Python-list mailing list