title: Python exec with a function chain producing NameError
body: <p>Consider the following script, which uses <code>exec</code> to define two functions, one of which calls the other:</p>
  <pre><code>def run_code():
    code = &quot;&quot;&quot;
  def foo():
    print('foo')
    return 1
  
  def bar():
    print('bar calls foo')
    return 1 + foo()
  
  result = bar()
  &quot;&quot;&quot;
  
    exec(code, globals(), locals())
    print('Result: {}'.format(locals()['result']))
  
  run_code()
  </code></pre>
  <p>I would expect to see the following output:</p>
  <pre><code>bar calls foo
  foo
  Result: 2
  </code></pre>
  <p>but instead, I get the following output+stacktrace:</p>
  <pre><code>bar calls foo
  Traceback (most recent call last):
    File &quot;minimal.py&quot;, line 17, in &lt;module&gt;
      run_code()
    File &quot;minimal.py&quot;, line 14, in run_code
      exec(code, globals(), locals())
    File &quot;&lt;string&gt;&quot;, line 10, in &lt;module&gt;
    File &quot;&lt;string&gt;&quot;, line 8, in bar
  NameError: name 'foo' is not defined
  </code></pre>
  <p>Interestingly, if the content of <code>run_code</code> is moved into the module level, then it works fine. However, if I then replace <code>globals()</code> or <code>locals()</code> with a new empty dictionary, it breaks once again. I also know that putting <code>def foo</code> inside <code>bar</code>'s body will make it work.</p>
  <p>Why is this error occurring, and what is the proper fix?</p>
  <p>(I know that <code>exec</code> is generally frowned upon. I am using it for good reason.)</p>