[Python-ideas] PEP 479: Change StopIteration handling inside generators

Chris Barker chris.barker at noaa.gov
Fri Nov 21 17:53:19 CET 2014


As someone who has written maybe one generator expression in production
code, I have little opinion on the PEP.

But as someone that teaches Python, I have a comment on:

On Fri, Nov 21, 2014 at 10:50:52PM +1100, Chris Angelico wrote:
> > Yes, this would be affected. This proposal causes a separation of
> > generators and iterators, so it's no longer possible to pretend that
> > they're the same thing.
>

 As pointed out by Steven, the _are_ the same thing. When I teach
interators and generators, I get a bit tangled up explaining what the
difference is, and why Python has both. This is what I say:

Conceptually ( outside of language constructs):

An "generator" is something that, well, generates value on the fly, as
requested, until there are no more to generate, and then terminates.

A "iterator" on the other had is something that produces the values in a
pre-existing sequence of values, until there are no more.

IN practice, python uses the exact same protocol (the iterator protocol --
__iter__, __next__) for both, so that you can write, e.g. a for loop, and
not have to know whether the underlying object you are looping through is
iterating or generating...

As you can write a "generator" in the sense above in a class that supports
the iterator protocol (and, can, in fact, write an "iterator" with a
generator function), then I say that generator functions really are only
syntactic sugar -- they are short and sweet and do much of the book keeping
for you.

But given all that keeping the protocols as similar as possible is a *good*
thing, not a bad one -- they should behave as much as possible teh same.

If StopIteration bubbles up from inside an iterator, wouldn't that silently
terminate as well?

Honestly, I'm a bit lost -- but my point is this -- generators and
iterators should behave as much the same as possible.

-Chris

-- 

Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker at noaa.gov
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20141121/608bfe8c/attachment-0001.html>


More information about the Python-ideas mailing list