Why does Python 3 exec() fail when specifying locals?
<p>The following executes without an error in Python 3:</p>

<pre><code>code = """
import math

def func(x):
    return math.sin(x)

func(10)
"""
_globals = {}
exec(code, _globals)
</code></pre>

<p>But if I try to capture the local variable dict as well, it fails with a <code>NameError</code>:</p>

<pre><code>&gt;&gt;&gt; _globals, _locals = {}, {}
&gt;&gt;&gt; exec(code, _globals, _locals)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
&lt;ipython-input-9-aeda81bf0af1&gt; in &lt;module&gt;()
----&gt; 1 exec(code, {}, {})

&lt;string&gt; in &lt;module&gt;()

&lt;string&gt; in func(x)

NameError: name 'math' is not defined
</code></pre>

<p>Why is this happening, and how can I execute this code while capturing both global and local variables?</p>

<p>From the <a href="https://docs.python.org/3/library/functions.html#exec" rel="nofollow"><code>exec()</code> documentation</a>:</p>

<blockquote>
  <p>Remember that at module level, globals and locals are the same dictionary. If <code>exec</code> gets two separate objects as <em>globals</em> and <em>locals</em>, the code will be executed as if it were embedded in a class definition.</p>
</blockquote>

<p>You passed in two separate dictionaries, but tried to execute code that requires module-scope globals to be available. <code>import math</code> in a class would produce a <em>local scope attribute</em>, and the function you create won't be able to access that as class scope names are not considered for function closures.</p>

<p>See <a href="https://docs.python.org/3/reference/executionmodel.html#naming-and-binding" rel="nofollow"><em>Naming and binding</em></a> in the Python execution model reference:</p>

<blockquote>
  <p>Class definition blocks and arguments to <code>exec()</code> and <code>eval()</code> are special in the context of name resolution. A class definition is an executable statement that may use and define names. These references follow the normal rules for name resolution with an exception that unbound local variables are looked up in the global namespace. The namespace of the class definition becomes the attribute dictionary of the class. The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods[.]</p>
</blockquote>

<p>You can reproduce the error by trying to execute the code in a class definition:</p>

<pre><code>&gt;&gt;&gt; class Demo:
...     import math
...     def func(x):
...         return math.sin(x)
...     func(10)
...
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  File "&lt;stdin&gt;", line 5, in Demo
  File "&lt;stdin&gt;", line 4, in func
NameError: name 'math' is not defined
</code></pre>

<p>Just pass in <em>one</em> dictionary.</p>

python python-3.x exec python-exec