[Tutor] Iterator vs. iterable cheatsheet, was Re: iter class

eryksun eryksun at gmail.com
Sat Jan 25 04:13:47 CET 2014


On Fri, Jan 24, 2014 at 8:50 AM, spir <denis.spir at gmail.com> wrote:
>
> xs is an iterator (__next__ is there), then Python uses it directly, thus
> what is the point of __iter__ there? In any case, python must check whether

Python doesn't check whether a type is already an iterator. It's
simpler to require that iterators implement __iter__, like any other
non-sequence iterable. This technically allows an iterator to return a
new iterator when __iter__ is called:

    class C:
        def __iter__(self): return D()
        def __next__(self): return 'C'

    class D:
        def __iter__(self): return C()
        def __next__(self): return 'D'

    it1 = iter(C())
    it2 = iter(it1)

    >>> next(it1)
    'D'
    >>> next(it2)
    'C'

That said, it's supposed to return self.


More information about the Tutor mailing list