gpt4 book ai didi

python - 在python中评估if的条件

转载 作者:行者123 更新时间:2023-11-28 22:48:36 25 4
gpt4 key购买 nike

我有 python 程序的 AST,想手动评估 if 语句的条件。

cond = node.test
b = eval(compile(cond,"<string>","eval"))
print b

node 是 If-Node,给我 TypeError: expected Expression node, got Compare,即使根据 ast 的 python 文档中的语法,Compare 是一个表达式。

有什么想法吗?

最佳答案

你有一个 ast.expr 子类,不是 ast.Expression 顶级节点。

compile() 只能接受一个 mod 对象,所以 ModuleInteractiveExpression,取决于 compile() 的第三个参数。对于 'eval',使用 ast.Expression()

您可以创建一个包含 ast.Compare 节点:

expr = ast.Expression(cond)

因为 abstract grammar定义为:

Expression(expr body)

你可以编译:

compile(expr, '<file>', 'eval')

演示:

>>> import ast
>>> code = "if foo == 'bar': pass"
>>> tree = ast.parse(code, '<file>', 'exec')
>>> cond = tree.body[0].test
>>> expr = ast.Expression(cond)
>>> compile(expr, '<file>', 'eval')
<code object <module> at 0x1067f6230, file "<file>", line 1>
>>> foo = 'baz'
>>> eval(compile(expr, '<file>', 'eval'))
False
>>> foo = 'bar'
>>> eval(compile(expr, '<file>', 'eval'))
True

关于python - 在python中评估if的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24913813/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com