如何用 Python AST 中的值替换变量名?
How do I replace a variable name with a value in a Python AST?
我希望我的用户能够在命令行中以 Python 语法输入算术表达式,并在运行时将变量名替换为值。我不想只使用 eval
,我想使用 Abstract Syntax Trees.
例如,假设我想用值 3.5
重写 AST 中的每个变量,然后对其求值。通过阅读文档,我想到了这个。
import ast
class RewriteName(ast.NodeTransformer):
def visit_Name(self, node):
return ast.copy_location(ast.Num(n=3.5, ctx=node.ctx), node)
tree = ast.parse('a + b', 'eval')
tree = RewriteName().visit(tree)
ast.fix_missing_locations(tree)
o = compile(tree, '<string>', 'eval')
print(eval(o))
我想打印 7.0
但我收到以下错误。
o = compile(tree, '<string>', 'eval')
TypeError: expected Expression node, got Module
我知道 AST 混淆了关于 Expression
和 Expr
的命名法,但我没能找到如何解决这个问题的示例。我尝试了 compile
的各种参数,包括 运行 它在 tree
的各个子节点上,认为其中之一可能是我需要的表达式,但到目前为止没有成功。
实现此功能的示例代码是什么?
我用错误的参数调用 ast.parse
。正确的叫法是
tree = ast.parse('a+b', '', eval)
(见上面的评论。)
我希望我的用户能够在命令行中以 Python 语法输入算术表达式,并在运行时将变量名替换为值。我不想只使用 eval
,我想使用 Abstract Syntax Trees.
例如,假设我想用值 3.5
重写 AST 中的每个变量,然后对其求值。通过阅读文档,我想到了这个。
import ast
class RewriteName(ast.NodeTransformer):
def visit_Name(self, node):
return ast.copy_location(ast.Num(n=3.5, ctx=node.ctx), node)
tree = ast.parse('a + b', 'eval')
tree = RewriteName().visit(tree)
ast.fix_missing_locations(tree)
o = compile(tree, '<string>', 'eval')
print(eval(o))
我想打印 7.0
但我收到以下错误。
o = compile(tree, '<string>', 'eval')
TypeError: expected Expression node, got Module
我知道 AST 混淆了关于 Expression
和 Expr
的命名法,但我没能找到如何解决这个问题的示例。我尝试了 compile
的各种参数,包括 运行 它在 tree
的各个子节点上,认为其中之一可能是我需要的表达式,但到目前为止没有成功。
实现此功能的示例代码是什么?
我用错误的参数调用 ast.parse
。正确的叫法是
tree = ast.parse('a+b', '', eval)
(见上面的评论。)