0
def make_accumulator(init):
    def accumulate(part): 
        init = init + part 
        return init
    return accumulate

A = make_accumulator(1)
print A(2)

gives me:-

Traceback (most recent call last):
  File "make-accumulator.py", line 8, in <module>
    print A(2)
  File "make-accumulator.py", line 3, in accumulate
    init = init + part 
UnboundLocalError: local variable 'init' referenced before assignment

Why is init not visible inside accumulate?

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
Himanshu
  • 2,384
  • 2
  • 24
  • 42

2 Answers2

1

That's because during parsing the inner function when Python sees the assignment init = init + part it thinks init is a local variable and it will only look for it in local scope when the function is actually invoked.

To fix it add init as an argument to accumulate with default value of init:

def make_accumulator(init):
    def accumulate(part, init=init): 
        init = init + part 
        return init
    return accumulate

Read: Why am I getting an UnboundLocalError when the variable has a value?

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
1
>>> def make_accumulator(init):
...     def accumulate(part): 
...         return init + part
...     return accumulate
... 
>>> make_accumulator(1)
<function accumulate at 0x7fe3ec398938>
>>> A(2)
3

Since you declare init inside accumulate, Python interprets it as local and therefore referenced before assignment. (Note that I removed the init = part).

I am definitely not an expert about this, but got the hint from these posts : Here and Here.

I guess someone could explain it better...

Community
  • 1
  • 1
Floran Gmehlin
  • 824
  • 1
  • 11
  • 34