编辑:问题与ast
模块无关。
只需使用exec
以下命令即可复制它:
y = None
exec("y = 5.0")
print(y) # prints 5.0
与
def foo():
y = None
exec("y = 5.0")
print(y)
foo() # prints None
原始问题:
我正在使用ast
模块以编程方式生成代码。我有以下代码,可以正常工作:
import ast
num = ast.Num(n=5.)
y = None
assign = ast.Assign(targets=[ast.Name(id='y', ctx=ast.Store())], value=num)
tree = ast.Module(body=[assign], type_ignores=[])
ast.fix_missing_locations(tree)
c = compile(tree, filename="", mode="exec")
exec(c) # replaces the value of 'y' with 5.0
print(y) # prints 5.0
但是,只要将此代码包装到函数中,它就会停止工作:
import ast
def foo():
num = ast.Num(n=5.)
y = None
assign = ast.Assign(targets=[ast.Name(id='y', ctx=ast.Store())], value=num)
tree = ast.Module(body=[assign], type_ignores=[])
ast.fix_missing_locations(tree)
c = compile(tree, filename="", mode="exec")
exec(c)
print(y)
foo() # prints None
这是我第一次看到在函数内部移动后python代码的行为有所不同。我已经检查过,分配也没有放在y
模块(本地)中:
print(y) # NameError: name 'y' is not defined
在函数中时,可以将分配捕获到任何字典中,这些字典将作为已执行语句的作用域:
def foo():
scope = {}
exec("y = 5.0", scope)
print(scope['y'])
foo() # prints 5.0
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句