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>

<pre><code>&gt;&gt;&gt; def make_accumulator(init):
...     def accumulate(part): 
...         return init + part
...     return accumulate
... 
&gt;&gt;&gt; make_accumulator(1)
&lt;function accumulate at 0x7fe3ec398938&gt;
&gt;&gt;&gt; A(2)
3
</code></pre>

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

<p>I am definitely not an expert about this, but got the hint from these posts : <a href="http://stackoverflow.com/questions/9264763/unboundlocalerror-in-python">Here</a> and <a href="http://stackoverflow.com/questions/4831680/function-inside-function">Here</a>.</p>

<p>I guess someone could explain it better...</p>

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