Generators and their next() and send() methods

Arnaud Delobelle arnodel at googlemail.com
Sat Nov 15 13:24:27 EST 2008


Thomas Mlynarczyk <thomas at mlynarczyk-webdesign.de> writes:

> Hello,
>
> I was playing around a bit with generators using next() and
> send(). And I was wondering why an extra send() method was introduced
> instead of simply allowing an argument for next().
>
> Also, I find it a bit counter-intuitive that send(42) not only "sets"
> the generator to the specified value, but yields the next value at the
> same time.

If you want to simply 'set' the generator (by which I take you mean
'change its state') without without iterating it one step, then what you
need is a class with an __iter__() method.  Then you can change the
state of the object between calls to next().  E.g.

>>> class MyGenerator(object):
...     def __init__(self, v): self.v = v
...     def __iter__(self):
...         for x in range(10):
...             yield self.v
... 
>>> g = MyGenerator(5)
>>> for i in g:
...     g.v = input("val:")
...     print i
... 
val:4
5
val:10
4
val:34
10
val:56
34
val:

Etc...

-- 
Arnaud



More information about the Python-list mailing list