为什么ast.literal_eval('5 * 7')失败? [英] Why does ast.literal_eval('5 * 7') fail?
问题描述
为什么 5 * 7
的字面值评估失败,而 5 + 7
的字面值评估没有失败?
Why does the literal evaluation of 5 * 7
fail, while 5 + 7
doesn't?
import ast
print(ast.literal_eval('5 + 7'))
# -> 12
print(ast.literal_eval('5 * 7'))
# ->
Traceback (most recent call last):
...
ValueError: malformed node or string: <_ast.BinOp object at ...>
文档没有对此进行解释。
我在回答后发现了这个问题关于这个问题:获取字符串的结果。
I found that problem after answering this question on SO: Getting the result of a string.
推荐答案
ast.literal_eval()
接受评估数据中的 +
,因为 5 + 2j
(复数 * )是有效的文字。 -
也是如此。为了使代码简单,没有尝试将 +
或-
排除为二进制运算符。
ast.literal_eval()
accepts +
in the evaluated data because 5+2j
(complex number*) are valid literals. The same applies to -
. To keep the code simple, no attempt is made to exclude +
or -
as a binary operators.
不允许其他运算符;该函数应该只接受文字,而不是表达式。
No other operators are allowed; the function is supposed to only accept literals, not expressions.
换句话说,即 5 + 7
的工作是一个错误,但是如果不中断对构造复数的支持,就很难修复它。 实现将使用范围限制为数字操作数,一元 +
和-
或其他二进制运算符(因此,您不能使用它们来连接列表或产生集合差异)。
In other words, that 5 + 7
works is a bug, but one that is hard to fix without breaking support for constructing complex numbers. The implementation limits the use to operands that are numbers, unary +
and -
, or other binary operators (so you can't use these to concatenate lists or produce a set difference).
另请参阅几个相关的Python bugtracker条目:# 25335 ast.literal_eval无法用前导 + 解析数字,#22525 ast.literal_eval()不执行文档所说的内容 和#4907 ast.literal_eval无法正确处理复数
Also see several related Python bugtracker entries: #25335 ast.literal_eval fails to parse numbers with leading "+", #22525 ast.literal_eval() doesn't do what the documentation says and #4907 ast.literal_eval does not properly handled complex numbers
* 从技术上讲, 2j
是有效的文字; Python将 5 + 2j
解析为 int(5)binop(+)complex(0,2)
,并且仅稍后在实际执行加法运算时,会从结果中生成 complex(5,2)
对象。
* Technically speaking, 2j
is a valid literal; Python parses 5+2j
as int(5) binop(+) complex(0, 2)
, and only later produces a complex(5, 2)
object from the result, when actually executing the addition.
这篇关于为什么ast.literal_eval('5 * 7')失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!