我有一个语法树
Tree(if, [Tree(condition, [Token(VARIABLE, 'age'), Token(ACTION_OPERATOR, '>'), Token(SIGNED_NUMBER, '18')]), Tree(result, [Tree(if, [Tree(condition, [Token(VARIABLE, 'salary'), Token(ACTION_OPERATOR, '>'), Token(SIGNED_NUMBER, '100000')]), Tree(result, [Token(STRING, 'success')]), Tree(condition, [Token(VARIABLE, 'salary'), Token(ACTION_OPERATOR, '<'), Token(SIGNED_NUMBER, '50000')]), Tree(result, [Token(STRING, 'fail')]), Tree(else, [Token(STRING, 'get_more_info')])])]), Tree(else, [Token(STRING, 'fail')])])
我将其转换为字符串:
if age > 18:
if salary > 100000:
print('success')
elif salary < 50000:
print('fail')
else:
print('get_more_info')
else:
print('fail')
我宣布变量:
age = 20
salary = 60000
尝试使用
执行此代码eval(code)
并收到错误
File "<string>", line 1
if age > 18:
^
SyntaxError: invalid syntax
答案 0 :(得分:2)
code = """
if age > 18:
if salary > 100000:
print('success')
elif salary < 50000:
print('fail')
else:
print('get_more_info')
else:
print('fail')"""
exec(code, {"age": 20, "salary": 60000})
# out: get_more_info
exec
接受代码字符串或代码对象。虽然eval
采用表达式。
或者,您始终可以通过compiling代码字符串预先评估(使用eval
)代码对象:
eval(compile(code, '<string>', 'exec'), {"age": 20, "salary": 60000})
# out: get_more_info
只是为了它的乐趣,可以使用eval
作为语法树而无需编译代码,但您的代码必须有所不同:
code = 'print(("success" if salary > 100000 else "fail" if salary < 50000 else "get_more_info") if age > 18 else "fail")'
eval(code, {"age": 20, "salary": 60000})
# out: get_more_info
这利用了Python的ternary条件,从技术上讲,它仍被视为表达式。
答案 1 :(得分:1)