generator object or 'send' method?

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue Feb 10 01:04:16 EST 2009


On Tue, 10 Feb 2009 05:28:26 +0000, John O'Hagan wrote:

> On Mon, 9 Feb 2009, Aaron Brady wrote:
>> Hello,
>>
>> I am writing a generator to return a sequence of numbers with some
>> variation.  The parameters of the variation can be changed by the
>> caller, even after the generator is started.
> [...]
> 
> 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




-- 
Steven



More information about the Python-list mailing list