generator object or 'send' method?

andrew cooke andrew at acooke.org
Tue Feb 10 13:30:05 CET 2009


steven probably knows this, but to flag the issue for people who are
looking at generators/coroutines for the first time: there's a little
"gotcha" about exactly how the two sides of the conversation are
synchronized.  in simple terms: send also receives.

unfortunately the example steven gave doesn't really show this, so i've
modified it below.  you can now see that the first next() after .send()
receives 2, not 1.  note that i am using python 3, so the .next() method
is .__next__() (the asymmetry between next and send seems odd to me, but
there you go).

(in a sense this is completely logical, but if you're used to the
asynchronous way the internet works, it can seem unintuitive)

how to handle this was one of the things the original post was asking
about (if i understood correctly).

>>> def gen(n):
...   while True:
...     obj = yield n
...     n += 1
...     if obj is not None: n = obj
...
>>> g = gen(5)
>>> next(g)
5
>>> g.__next__()
6
>>> g.send(1)
1
>>> next(g)
2

andrew


Steven D'Aprano wrote:
> On Tue, 10 Feb 2009 05:28:26 +0000, John O'Hagan wrote:
>> I would love to see a simple code example of this if you have one; I've
>> been wanting to do this but couldn't even get started.
>
> Is this too simple?
>
>>>> def gen(n):
> ...     while True:
> ...             obj = yield n
> ...             if obj is not None: n = obj
> ...
>>>> g = gen(5)
>>>> g.next()
> 5
>>>> g.next()
> 5
>>>> g.send(12)
> 12
>>>> g.next()
> 12





More information about the Python-list mailing list