[Python-Dev] PEP 342: simple example, closure alternative

Ian Bicking ianb at colorstudy.com
Thu Aug 25 22:12:35 CEST 2005

Phillip J. Eby wrote:
> At 02:10 PM 8/25/2005 -0500, Ian Bicking wrote:
>>I was trying to translate a pattern that uses closures in a language
>>like Scheme (where closed values can be written to) to generators using
>>PEP 342, but I'm not clear exactly how it works; the examples in the PEP
>>have different motivations.  Since I can't actually run these examples,
>>perhaps someone could confirm or debug these:
>>A closure based accumulator (using Scheme):
>>(define (accum n)
>>  (lambda (incr)
>>   (set! n (+ n incr))
>>   n))
>>(define s (accum 0))
>>(s 1) ; -> 1 == 0+1
>>(s 5) ; -> 6 == 1+5
>>So I thought the generator version might look like:
>>def accum(n):
>>     while 1:
>>         incr = (yield n) or 0
>>         n += incr

Bah, I don't know why this had me so confused.  Well, I kind of know 
why.  So maybe this example would be better written:

def accum(n):
     incr = yield       # wait to get the first incr to be sent in
     while 1:
         n += incr
         incr = yield n # return the new value, wait for next incr

This way it is more explicit all around -- the first call to .next() is 
just setup, kind of like __init__ in an object, except it has to be 
explicitly invoked.
Ian Bicking  /  ianb at colorstudy.com  /  http://blog.ianbicking.org

More information about the Python-Dev mailing list