title: Where does nonlocal variables live after the enclosing function's call ends
body: <p>My understanding is that when the enclosing function call ends the stack frames must be destroyed. So where do variables inside an enclosing function that are free variable relative to inner function continue to live on?</p>
  <p>Let me draw some (trivial) example. When I click &quot;increase&quot; button twice followed by &quot;decrease&quot; twice, <code>var</code> increments to 1, 2 and decrements to 1, 0. But, by the time the buttons are clicked <code>constructUI</code> already ends, so <code>var</code> cannot live in <code>constructUI</code>'s stack frame and I wonder where does the variable live?</p>
  <pre><code>import ipywidgets as widgets
  from IPython.display import display
  
  def constructUI():
      b1 = widgets.Button(description=&quot;increase&quot;)
      b2 = widgets.Button(description=&quot;decrease&quot;)
      display(b1, b2)
  
      var = 0
      def increment(b):
          nonlocal var
          var += 1
          print(f&quot;var is {var}&quot;)
      def decrement(b):
          nonlocal var
          var -= 1
          print(f&quot;var is {var}&quot;)
      
      b1.on_click(increment)
      b2.on_click(decrement)
  
  constructUI()
  </code></pre>
  <p><a href="https://i.stack.imgur.com/Erhb8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Erhb8.png" alt="enter image description here" /></a></p>