python:var';s命名空间代码eval编译的ast代码

python:var';s命名空间代码eval编译的ast代码,python,namespaces,eval,abstract-syntax-tree,python-unittest,Python,Namespaces,Eval,Abstract Syntax Tree,Python Unittest,使用python3.4并测试ast解析。这是测试代码 import ast import unittest class TestAST(unittest.TestCase): def test_ast(self): #compileobj = compile(ast.parse("x=42"), '<input>', mode="exec") #compile(ast.parse("x=42"), '<input>', mod

使用python3.4并测试ast解析。这是测试代码

import ast
import unittest


class TestAST(unittest.TestCase):

    def test_ast(self):
        #compileobj = compile(ast.parse("x=42"), '<input>', mode="exec")
        #compile(ast.parse("x=42"), '<input>', mode="exec")
        eval(compile(ast.parse("x=42"), '<input>', mode="exec"))
        self.assertTrue(x == 42)
        pass


if __name__ == '__main__':
    unittest.main()
在ipython中评估时:x可以如下所示:

In [3]:  eval(compile(ast.parse("x=42"), '<input>', mode="exec"))

In [4]: x
Out[4]: 42
跑步后。它显示42

更详细地说,在func中调用此函数也失败

def test_eval():
    eval(compile(ast.parse("y=42"), '<input>', mode="exec"))
    print ("y is ", y)

if __name__ == '__main__':
    #unittest.main()
    test_eval()
def test_eval():
eval(compile(ast.parse(“y=42”),“”,mode=“exec”))
打印(“y是”,y)
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
#unittest.main()
测试评估()

在Python 3中,不能动态创建新的本地名称。这些都是在函数编译成字节码的时候被嵌入的。相反,您需要将字典传递给
exec
,以便在该语句中用作局部变量

def test_ast(self):
    localvars = {}
    eval(compile(ast.parse("x=42"), '<input>', mode="exec"), localvars)
    self.assertTrue(localvars["x"] == 42)
def测试(自):
localvars={}
eval(compile(ast.parse(“x=42”),“”,mode=“exec”),localvars)
self.assertTrue(localvars[“x”]==42)

回溯链接到文件
test\u ast.py
中的错误,该错误与
eval
eval已完成的行无关。所以这里的问题是为什么x找不到。如果x=42,则已计算。
def test_eval():
    eval(compile(ast.parse("y=42"), '<input>', mode="exec"))
    print ("y is ", y)

if __name__ == '__main__':
    #unittest.main()
    test_eval()
def test_ast(self):
    localvars = {}
    eval(compile(ast.parse("x=42"), '<input>', mode="exec"), localvars)
    self.assertTrue(localvars["x"] == 42)