title: Local and global references with UnboundLocalError
body: <p>I don't quite understand why the code</p>
  
  <pre><code>def f():
      print(s)
  
  s = "foo"
  f()
  </code></pre>
  
  <p>runs perfectly fine but</p>
  
  <pre><code>def f():
      print(s)
      s = "bar"
  
  s = "foo"
  f()
  </code></pre>
  
  <p>gives me UnboundLocalError. I know that I can fix this by declaring <em>s</em> as a global variable inside the function or by simply passing <em>s</em> an an argument into the function.</p>
  
  <p>Still I don't understand how python seemingly knows whether or not s is referenced inside the function before the line has been executed? Does python make some sort of list of all local variable references when the function is read into the global frame?</p>