unexpected behaviour of `global` variables in Python
<pre><code>prev, prev_re = '', (None) # these are globals

def find(h, p='', re=None):
    print h, p, re
    #global prev, prev_re
    if p == '' and prev == h: return prev_re
    prev, prev_re = h, re
    return re
print find ("abc")
</code></pre>

<p>results in this error:</p>

<pre><code>    if p == '' and prev == h: return prev_re
UnboundLocalError: local variable 'prev' referenced before assignment
$ 
</code></pre>

<p><strong>But</strong> if I comment the before last line of <code>find</code>,</p>

<pre><code>prev, prev_re = '', (None)

def find(h, p='', re=None):
    print h, p, re
    #global prev, prev_re
    if p == '' and prev == h: return prev_re
    #prev, prev_re = h, re
    return re
print find ("abc")
</code></pre>

<p>the code runs correctly, as expected, without error.</p>

<p>My questions are why in the first case it does not find the global variable  <code>prev</code>, and why in the second case it does find the global variable in the <code>if</code>-condition ?</p>

<p>edit: please help me understand the details of the structure of environments, to understand why the interpretor cannot find the variable.</p>
