title: Do Python interpreter resolve variable references when a function is defined but not called?
body: <p>First of all, <a href="https://stackoverflow.com/questions/22997011/does-python-automatically-clear-up-objects">this post</a> does NOT answer my question or give me any guide to answer my question at all. </p>
  
  <p>My question is about mechanism function resolving non-local variables.</p>
  
  <p>Code</p>
  
  <pre><code># code block 1
  def func():
      vals = [0, 0, 0]
      other_vals = [7, 8, 9]
      other = 12
  
      def func1():
          vals[1] += 1
          print(vals)
  
      def func2():
          vals[2] += 2
          print vals
  
      return (func1, func2)
  
  f1, f2 = func()
  </code></pre>
  
  <p>Try to run <code>f1</code>, <code>f2</code>:</p>
  
  <pre><code>&gt;&gt;&gt; f1()
  [0, 1, 0]
  &gt;&gt;&gt; f2
  [0, 1, 2]
  </code></pre>
  
  <p>This shows that the object previously referred by <code>vals</code> are shared by <code>f1</code> and <code>f2</code>, and not garbage collected after execution of <code>func</code>.</p>
  
  <p>Will objects referred by <code>other_vals</code> and <code>other</code> be garbage collected? I think so. But how does Python decide not to garbage collect <code>vals</code>?</p>
  
  <p><strong>Assumption 1</strong> </p>
  
  <p>Python interpreter will resolve variable names within <code>func1</code> and <code>func2</code> to figure out references inside the function, and increase the reference count of <code>[0, 0, 0]</code> by 1 preventing it from garbage collection after the <code>func</code> call. </p>
  
  <p>But if I do </p>
  
  <pre><code># code block 2
  def outerfunc():
      def innerfunc():
          print(non_existent_variable)
  f = outerfunc()
  </code></pre>
  
  <p>No error reported. Further more</p>
  
  <pre><code># code block 3
  def my_func():
      print(yet_to_define)
  yet_to_define = "hello"
  </code></pre>
  
  <p>works.</p>
  
  <p><strong>Assumption 2</strong> 
  Variable names are resolved dynamically at run time. This makes observations in code block 2 and 3 easy to explain, but how did the interpreter know it need to increase reference count of <code>[0, 0, 0]</code> in code block 1?</p>
  
  <p>Which assumption is correct? </p>