title: Accessing variables defined in enclosing scope
body: <p>From the <a href="https://google.github.io/styleguide/pyguide.html#Lexical_Scoping" rel="noreferrer">Google Style Guide</a> on lexical scoping:</p>
  
  <blockquote>
    <p>A nested Python function can refer to variables defined in enclosing
    functions, but can not assign to them.</p>
  </blockquote>
  
  <p>Both of these seem to check out at first:</p>
  
  <pre><code># Reference
  def toplevel():
      a = 5
      def nested():
          print(a + 2)
      nested()
      return a
  toplevel()
  7
  Out[]: 5
  
  # Assignment
  def toplevel():
      a = 5
      def nested():
          a = 7 # a is still 5, can't modify enclosing scope variable
      nested()
      return a
  toplevel()
  Out[]: 5
  </code></pre>
  
  <p>So why, then, does a combination of both reference and assignment in the nested function lead to an exception?</p>
  
  <pre><code># Reference and assignment
  def toplevel():
      a = 5
      def nested():
          print(a + 2)
          a = 7
      nested()
      return a
  toplevel()
  # UnboundLocalError: local variable 'a' referenced before assignment
  </code></pre>