[Python-ideas] Generators are iterators
Steven D'Aprano
steve at pearwood.info
Wed Dec 10 15:18:59 CET 2014
On Wed, Dec 10, 2014 at 12:36:59PM +0000, Oscar Benjamin wrote:
> The PEP says:
>
> """
> Under this proposal, generators and iterators would be distinct, but
> related, concepts. Like the mixing of text and bytes in Python 2, the
> mixing of generators and iterators has resulted in certain perceived
> conveniences, but proper separation will make bugs more visible.
> """"
>
> This is just plain false.
I certainly hope so.
Currently, generators are iterators: they obey the iterator protocol and
the Iterator ABC correctly registers them as instances.
py> def gen():
... yield 1
...
py> it = gen()
py> iter(it) is it # Iterator protocol is obeyed.
True
py> hasattr(it, '__next__')
True
py> from collections.abc import Iterator
py> isinstance(it, Iterator) # And registered with the ABC.
True
Surely this isn't going to change? If it does, I expect that's going to
break an enormous amount of code.
If generators are to cease to be iterators, what will they be?
> I propose to abolish this notion that generators are not iterators and
> to amend the text of the PEP to unambiguously state that generators
> are iterators regardless of any changes to the way they propagate
> StopIteration from the executing frame.
Sounds reasonable to me.
--
Steven
More information about the Python-ideas
mailing list