Re: accumulator generators



Cameron <cameronlarue@xxxxxxxxx> writes:

I was reading this <a href="this http://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


--
Arnaud
.



Relevant Pages

  • Re: What makes an iterator an iterator?
    ... |> by improperly writing .next as a generator function ... | What iterator rule states that .next can't be a generator function? ... def f: ...
    (comp.lang.python)
  • Re: accumulator generators
    ... Graham articleand he builds an accumuator generator function in ... def foo: ... return bar ...
    (comp.lang.python)
  • Re: recursive file editing
    ... > I've written a little generator function to hide some of the clumsiness: ... > def files: ... > for path, folders, files in os.walk: ...
    (comp.lang.python)
  • Re: Silly question re: for i in sys.stdin?
    ... The iterator for files is a little bit like this generator function: ... the read from the tty will block until sizehint ... def lines: # untested ...
    (comp.lang.python)
  • Re: Interesting little "gotcha" with generators
    ... > def compileOuter: ... > "compileOuter" is a generator function which is implemented in ... A generator is simply a function which when called returns an iterator, ...
    (comp.lang.python)