Python: How can I run eval() in the local scope of a function
<p>I try to use eval() in a local scope of a function. However it always evaluate in the global scope.</p>

<p>Self contained examples:</p>

<p>1- This code works:</p>

<pre><code>var1 = 1
var2 = 2
var3 = 3    
myDict = dict((name, eval(name)) for name in ["var1",
                                              "var2",
                                              "var3"])
print(myDict["var1"])
</code></pre>

<p>2- Throws <code>NameError</code> for <code>lvar1</code></p>

<pre><code>def test1():
   lvar1 = 1
   lvar2 = 2
   lvar3 = 3
   myDict = dict((name, eval(name)) for name in ["lvar1",
                                                 "lvar2",
                                                 "lvar3"])
   print(myDict["lvar1"])
</code></pre>

<p>3- Same outcome as 2.</p>

<pre><code>def test2():
    lvar1 = 1
    lvar2 = 2
    lvar3 = 3
    myDict = dict((name, eval(name), locals()) for name in ["lvar1",
                                                            "lvar2",
                                                            "lvar3"])
    print(myDict["lvar1"])
</code></pre>