为什么ast.literal_eval()似乎忽略声明的变量? [英] Why does ast.literal_eval() seem to ignore declared variables?
问题描述
我听说ast.literal_eval比eval()安全得多,但是在更改代码时,出现格式错误的字符串/节点错误。
I have heard that ast.literal_eval is much safer than eval(), but while changing my code, I am getting 'malformed string/node' errors.
例如:
bar = False
incorrect = {"foo":bar}
correct = {"foo":"bar"}
ast.literal_eval(incorrect)
返回错误,但
ast.literal_eval(correct)
返回期望的{ foo: bar}
returns the expected {"foo":"bar"}
为什么第一次评估不返回{ foo:False}
Why doesn't the first evaluation return {"foo":False}
推荐答案
因为这并不意味着这样做。从文档中:
Because it is not meant to do that. From the documentation:
安全地评估表达式节点或包含Python表达式的Unicode或Latin-1编码的
字符串。提供的字符串或节点可能
仅包含以下Python文字结构:字符串,
数字,元组,列表,字典,布尔值和无。
Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
ast.literal_eval
和 eval
的意思是将字符串表示形式转换为将python代码转换为...有效的python代码。
ast.literal_eval
and eval
are meant to turn a string representation of python code into ...valid python code.
这将不起作用:
>>> ast.literal_eval({"foo": "bar"})
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/lib/python2.7/ast.py", line 80, in literal_eval
return _convert(node_or_string)
File "/usr/lib/python2.7/ast.py", line 79, in _convert
raise ValueError('malformed string')
ValueError: malformed string <-- Telltale right here.
这是因为您已经具有要评估的有效python结构。
That is because you already have a valid python structure which you are attempting to evaluate.
如果将引号括起来,它将创建一个字典:
If you put quotes around the whole thing instead, it will create a dictionary:
>>> ast.literal_eval('{"foo": "bar"}')
{'foo': 'bar'}
这篇关于为什么ast.literal_eval()似乎忽略声明的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!