generator/coroutine terminology

Chris Angelico rosuav at gmail.com
Fri Mar 13 07:32:34 EDT 2015


On Fri, Mar 13, 2015 at 8:12 PM, Rustom Mody <rustompmody at gmail.com> wrote:
> On Friday, March 13, 2015 at 1:53:50 PM UTC+5:30, Chris Angelico wrote:
>> On Fri, Mar 13, 2015 at 4:28 PM, Rustom Mody  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".
>
> Nice demo of the same confusing terminology we are talking about.
>
> When I say "expect generators to close" I mean 'generator-instances' ie at runtime
>
> When you say "expect both to close with return" you are talking of program-texts
> ie the 'factory'
>
> [Or I am guilty of the same I am accusing python of]

Well, if you're going to discuss the specifics of terminology, we'd
best figure out what "close" means :)

You spoke of generators closing "with" StopIteration. Does that mean
that, once a generator closes, it raises StopIteration? That's the job
of the next() method, in effect. Or do you mean that raising
StopIteration will terminate the generator? That won't be true
forever, and shouldn't be relied on - just use "return".

If you use the close() method, Python throws a GeneratorExit into your
generator. But unless you have something that catches that, you
shouldn't need to worry about it; all you need to know is that you
call close() and the function cleanly terminates. Like I said, there
are implementation details that don't usually matter.

ChrisA



More information about the Python-list mailing list