【发布时间】:2019-09-12 05:23:32
【问题描述】:
编辑:问题与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
【问题讨论】:
标签: python abstract-syntax-tree