[Python-ideas] generator vs iterator etc. (was: How assignment should work with generators?)
ncoghlan at gmail.com
Tue Nov 28 07:14:39 EST 2017
On 28 November 2017 at 16:11, Stephen J. Turnbull
<turnbull.stephen.fw at u.tsukuba.ac.jp> wrote:
> Steven D'Aprano writes:
> > The subset of iterators which are created as generators are *also*
> > called generators,
> As long as we're being precise, I don't think that is precisely correct:
> >>> (x for x in range(1))
> <generator object <genexpr> at 0x10dee5e08>
> >>> iter(range(1))
> <range_iterator object at 0x10dab83f0>
> >>> iter((1,))
> <tuple_iterator object at 0x10df109b0>
> The two iterators have the same duck-type, the generator is different.
> A generator (object) is, of course, an interable.
While it's not obvious with the genexp (since they're anonymous), the
main reason for the difference in the repr layouts here is just
because generator iterators can have names:
>>> def g(): yield
<generator object g at 0x7f93e5e41258>
So the statement that "generator iterators are iterators" is correct.
The functions that create them are called generator functions because
they really are functions:
<function g at 0x7f93f17f1ea0>
What's more unfortunate here is that the usage of "generator" in the
generator-iterator representation doesn't actually align with the
preferred terminology in the documentation:
So I can understand the confusion here.
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas