George Sakkis <[EMAIL PROTECTED]> writes:
> On May 31, 4:19 am, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
>> Cameron <[EMAIL PROTECTED]> writes:
>> > I was reading this <a href="thishttp://www.paulgraham.com/icad.html">Paul
>> > Graham article</a> and he builds an accumuator generator function in
>> > the appendix. His looks like this:
>>
>> > <pre>
>> > def foo(n):
>> > s = [n]
>> > def bar(i):
>> > s[0] += i
>> > return s[0]
>> > return bar
>> > </pre>
>>
>> > Why does that work, but not this:
>>
>> > <pre>
>> > def foo(n):
>> > s = n
>> > def bar(i):
>> > s += i
>> > return s
>> > return bar
>> > </pre>
>>
>> Others have explained why, but this looks like "pythonized LISP" to
>> me. I would rather use a generator function:
>>
>> def foo(n):
>> while True:
>> n += yield n
>>
>> Although the problem is that you can't send it values the first time
>> round!
>>
>> >>> bar = foo('s')
>> >>> bar.next()
>> 's'
>> >>> bar.send('p')
>> 'sp'
>> >>> bar.send('am')
>>
>> 'spam'
>>
>> But:
>>
>> >>> bar = foo(3)
>> >>> bar.send(2)
>>
>> Traceback (most recent call last):
>> File "<stdin>", line 1, in <module>
>> TypeError: can't send non-None value to a just-started generator
>
> I find the "pythonized LISP" solution more understandable, even
> without the initial next() requirement. YMMV
>
> George
In that case a class may be better? IMHO, what is such a natural
idiom in LISP does not translate well literally into Python.
class Foo(object):
def __init__(self, n):
self.s = n
def __call__(self, i)
self.s += i
return self.s
Anything to avoid the mutable container trick! Of course 'nonlocal'
takes care of this in py3k. I have missed the absence of 'nonlocal' a
lot, but now that it is around the corner, I grow less sure about it.
--
Arnaud
--
http://mail.python.org/mailman/listinfo/python-list