title: python variable scope in nested functions
body: <p>I am reading this <a href="http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/" rel="nofollow">article</a> about decorator.</p>
  
  <p>At <strong>Step 8</strong> , there is a function defined as:</p>
  
  <pre><code>def outer():
      x = 1
      def inner():
         print x # 1
      return inner
  </code></pre>
  
  <p>and if we run it by:</p>
  
  <pre><code>&gt;&gt;&gt; foo = outer()
  &gt;&gt;&gt; foo.func_closure # doctest: +ELLIPSIS
  </code></pre>
  
  <p>it doesn't print x. According to the explanation :</p>
  
  <blockquote>
    <p>Everything works according to Python’s scoping rules - x is a local
    variable in our function outer. When inner prints x at point #1 Python
    looks for a local variable to inner and not finding it looks in the
    enclosing scope which is the function outer, finding it there.</p>
    
    <p><strong>But what about things from the point of view of variable lifetime? Our
    variable x is local to the function outer which means it only exists
    while the function outer is running. We aren’t able to call inner till
    after the return of outer so according to our model of how Python
    works, x shouldn’t exist anymore by the time we call inner and perhaps
    a runtime error of some kind should occur.</strong></p>
  </blockquote>
  
  <p>However, I don't really understand what the second paragraph means. </p>
  
  <p>I understand inner() does get the value of x but why it doesn't print x out?</p>
  
  <p>thanks</p>
  
  <p><strong>UPDATE</strong>:</p>
  
  <p>Thanks all for the answers. Now I understand the reason.
  the "<strong>return inner</strong>" is just a <strong>pointer</strong> to inner() but it doesn't get executed, that is why inner() doesn't print x as it <strong>is not called at all</strong></p>