Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

python - Why does ast.literal_eval('5 * 7') fail?

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 ...>

The documentation doesn't explain this.

I found that problem after answering this question on SO: Getting the result of a string.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...