Re: accumulator generators



On May 30, 1:04 pm, "Diez B. Roggisch" <de...@xxxxxxxxxxxxx> wrote:
Cameron schrieb:



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>

Because python's static analysis infers s as being a variable local to
bar in the second case - so you can't modify it in the outer scope.

In the future, you may declare

def bar(i):
     nonlocal s
     ...

Diez

thanks for the response. Just to make sure I understand- Is the reason
it works in the first case because s[0] is undefined at that point (in
bar), and so python looks in the outer scope and finds it there?

Cameron

.



Relevant Pages

  • Re: Self function
    ... Python ... giving the programmer the ability to have a function refer to ... def parrot: ...     print inspect.getmembers ...
    (comp.lang.python)
  • Re: What c.l.pys opinions about Soft Exception?
    ... Actually, the latter is even less cluttered, misses a raise - if pure number ... Exception that aren't handled when no handler exists for it. ...     raise_soft ... def a_equal_b: ...
    (comp.lang.python)
  • Re: multiprocessing question/error
    ...     def calcula: ... def m1: ... from multiprocessing import Process, Pool ... def m2(self, arg): ...
    (comp.lang.python)
  • Re: How to launch a function at regular time intervals ?
    ...     func.start ... from datetime import datetime ... """Write timestamp in a file every 10 seconds in separate ... def stop: ...
    (comp.lang.python)
  • Re: question of style
    ...     if self.lower is None: ... values- Iterate through the values in sort order. ... def insert: ...
    (comp.lang.python)