generator/coroutine terminology

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Mar 12 23:30:06 EDT 2015


Rustom Mody wrote:

> On Thursday, March 12, 2015 at 11:25:32 PM UTC+5:30, Marko Rauhamaa wrote:
>> Rustom Mody :
>> 
>> > I guess we need
>> > 1. A clear ontology of the base concepts (which is a buzzword for
>> > nailed-down terminology)
>> 
>> According to the documentation, a function whose definition contains a
>> yield statement is a generator:
>> 
>>    Using a yield expression in a function's body causes that function to
>>    be a generator.
>> 
>>    <URL: https://docs.python.org/3/reference/expressions.html#yield-exp
>>    ressions>
>> 
>>    generator
>>       A function which returns an iterator.
>> 
>>    <URL: https://docs.python.org/3/glossary.html#term-generator>
>> 
>> Apparently, what we have here is a discrepancy between the documentation
>> and the CPython implementation.
>> 
>> In a word, it's a bug (somewhere).
> 
> Throwing out some thought for better terminology.
> [Yeah needs to be chewed on a bit...]
> 
> With respect to my example above:
> 
> def foo(x):
>    yield x+1
>    yield x+2
> 
> 
> g = foo(2)
> 
> Generator-instance: g
> Generator-factory: foo
> Generator: Concept in python (ontology) elaborated in terms of the above

I think that is is reasonable. I would include "generator function" as a
synonym for generator factory. (Factories are more inclusive than
functions -- a factory could include a class with a "make_generator"
method, for example.)

Where the distinction is clear, or not important, than calling both g and
foo "generators" is acceptable shorthand. I realise that can be confusing
to beginners, but jargon often is confusing to beginners until they have
learned enough to be able to correctly interpret things in context.


> Situation with coroutines is worse
> [Or I cant think of good terms...]

Not really. The difference between a coroutine and a generator is mostly in
usage, that is, intent. They both use the same type, they both have send
methods, they both are generated the same way. If you are foolish, you can
even mix generator-behaviour and coroutine-behaviour in the same function:


py> def g():
...     yield 1
...     yield 2
...     x = yield 3
...     yield x + 1000
...
py> a = g()
py> next(a)
1
py> next(a)
2
py> next(a)
3
py> a.send(99)
1099

But don't do that.

So as far as Python is concerned, a coroutine is just a generator instance
which you use in a particular way, not a different kind of object. So I
would use similar terminology:

A generator function/factory returns a generator instance, which we use as a
coroutine, so we can call it a coroutine.



-- 
Steven




More information about the Python-list mailing list