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.
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).
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
* 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…