为什么 ast.literal_eval('5 * 7') 会失败? [英] Why does ast.literal_eval('5 * 7') fail?

查看:30
本文介绍了为什么 ast.literal_eval('5 * 7') 会失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 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 ...>

文档没有解释一下.

我在 SO 上回答这个问题后发现了这个问题:获取字符串的结果.

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 错误跟踪器条目:#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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆