On Fri, Mar 13, 2015 at 4:28 PM, Rustom Mody <rustompm...@gmail.com> wrote:
> And even there I would expect generators to close with StopIteration
> Whereas I would expect coroutines to close (on close method) with 
> GeneratorExit
> [Ive not thought all this through properly so may be off the mark]

I expect both of them to close with "return". You can throw
GeneratorExit into a generator, but that's an implementation detail
more than anything else (same as the throwing of SystemExist is, and
for the same reason). When any iterator is exhausted, next() will
raise StopIteration rather than returning something; if you're simply
iterating over a generator, you can treat StopIteration as an
implementation detail too:

def squares_up_to(top):
    for n in range(top):
        if n*n > top: return
        yield n*n

for sq in squares_up_to(50):
    print(sq)

You don't need to be concerned about all those little details of
resuming and stack frames and so on. You definitely don't need to
worry about strange interactions around a "with" block inside the
generator - you can confidently trust that everything will behave
correctly. As it happens, this notion of "behaving correctly" is
largely implemented using exceptions, but if it were implemented with
a bunch of special cases in the CPython source code, it wouldn't
matter.

Write idiomatic source code and don't worry about the details. Learn
how things work if you're curious, but it's seldom going to matter.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to