[Python-ideas] Generators are iterators

Steven D'Aprano steve at pearwood.info
Sat Dec 13 14:36:22 CET 2014


On Fri, Dec 12, 2014 at 03:22:32PM -0800, Andrew Barnert wrote:

> In Python, the term "Iterator" is just as consistent and meaningful as 
> in all these other languages. The fact that some people confuse 
> iterables and iterators isn't a reason to abandon this simplicity. 
[...]

+1 to this.


But:

> The things we need to be clear about here are the things that _dont't_ 
> have an official name. In particular, the thing that's built from 
> calling a generator function or evaluating a generator expression and 
> used by the generator.__next__ method is not a generator, a generator 
> function, a generator function body, an iterator, or anything else 
> with a name in the language. And that's what's confusing people.

I don't know what thing you are referring to. If I write this:

py> def gen():
...     yield 1
...
py> it = gen()

then `gen` is a function. It's a specific kind of function that uses 
"yield", and the name for that is a generator function. Informally, 
sometimes people call it a "generator", which is a bad habit due to the 
possibility of confusing `gen` with `it`, but since it is quite rare to 
be in a position where such confusion can occur (PEP 479 and related 
discussions not withstanding), we can often get away with such sloppy 
terminology.

Also, `it` is an iterator. It's also a generator:

py> type(it)
<class 'generator'>

The same applies to generator expressions:

py> type(c for c in "aaa")
<class 'generator'>

So I'm not sure which mysterious object you are referring to that 
doesn't have a standard name. Can you give a concrete example?



-- 
Steven


More information about the Python-ideas mailing list