Unbound Local Error when Assigning to Function Arg
<pre><code>def make_accumulator(init):
    def accumulate(part): 
        init = init + part 
        return init
    return accumulate

A = make_accumulator(1)
print A(2)
</code></pre>

<p>gives me:-</p>

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

<p>Why is init not visible inside accumulate? </p>

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

<p>To fix it add <code>init</code> as an argument to <code>accumulate</code> with default value of <code>init</code>:</p>

<pre><code>def make_accumulator(init):
    def accumulate(part, init=init): 
        init = init + part 
        return init
    return accumulate
</code></pre>

<hr>

<p>Read: <a href="https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value" rel="nofollow">Why am I getting an UnboundLocalError when the variable has a value?</a></p>

python function python-3.x scope python-2.x