title: UnboundLocalError: local variable referenced before assignment in python closure
body: <p>I implemented two simple closures in Python. To me, they looks the same, but one works and the other doesn't.</p>
  
  <p>The working one is:</p>
  
  <pre><code>def makeInc(x, y):
      def inc():
          return y + x
      return inc
  
  inc5 = makeInc(5, 10)
  inc10 = makeInc(10, 5)
  
  inc5 () # returns 15
  inc10() # returns 15
  </code></pre>
  
  <p>But the second one doesn't work:</p>
  
  <pre><code>import os
  def linker(dest, filename):
      print filename
      def link(): 
          if os.path.isfile(filename): # line 17
              filename = os.path.join(os.getcwd(), filename)
              dest = os.path.join(dest, filename)
              y = rawinput('[y]/n: ln -sf %s %s' % (dest, filename))
              if y == 'n':
                  return 1
              else:
                  return os.system('ln -sf %s %s' %(dest, filename))
          else:
              return -1
      return link
  
  l = linker('~', '.vimrc')
  l()  # line 30
  </code></pre>
  
  <p>It faults at the first line of <code>link()</code> when executing <code>l()</code>:</p>
  
  <pre><code>Traceback (most recent call last):
    File "test.py", line 30, in &lt;module&gt;
      l()
    File "test.py", line 17, in link
      if os.path.isfile(filename):
  UnboundLocalError: local variable 'filename' referenced before assignment
  </code></pre>
  
  <p>They seem identical to me so I don't understand why the second one doesn't work. Any idea?</p>