Skip to main content
 首页 » 编程设计

python : var's namespace code eval compiled ast code

2024年11月01日12dyllove98

使用 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() 

python test.py 我得到这样的错误:

Traceback (most recent call last): 
  File "qocean\test\test_ast.py", line 13, in test_ast 
    self.assertTrue(x == 42) 
NameError: name 'x' is not defined 

虽然在 ipython 中评估它:x 可以这样看:

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

所以问题是,虽然我不能使用 var "x",因为 eval 代码在源代码和 ipython eval environemt 中是相同的。有什么区别?

########################################## #

更新:好像和unittest模块有关,在main()中修改测试代码,会成功。

if __name__ == '__main__': 
    eval(compile(ast.parse("x=42"), '<input>', mode="exec")) 
    print (x) 

运行后。它显示 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() 

请您参考如下方法:

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

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