[Python-Dev] PEP 342: simple example, closure alternative
Phillip J. Eby
pje at telecommunity.com
Thu Aug 25 21:23:10 CEST 2005
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
>
> >>> s = accum(0)
> >>> s.next()
The initial next() will yield 0, not None.
> >>> s.send(1)
>0
1
> >>> s.send(5)
>1
6
> >>> s.send(1)
>6
7
>Is the order of the output correct? Is there a better way to write
>accum, that makes it feel more like the closure-based version?
>
>Is this for loop correct?
>
> >>> s = accum(0)
> >>> for i in s:
>... if i >= 10: break
>... print i,
>... assert s.send(2) == i
>0 2 4 6 8
The assert will fail on the first pass. s.send(2) will == i+2, e.g.:
>>> s = accum(0)
>>> for i in s:
... if i>=10: break
... print i,
... assert s.send(2) == i+2
...
0 2 4 6 8
More information about the Python-Dev
mailing list