python中使用eval() 和 ast.literal_eval()的区别 分类: ...

空扰寡人 提交于 2019-12-03 07:40:29

eval函数在python中做数据类型的转换还是很有用的。它的作用就是把数据还原成它本身或者是能够转化成的数据类型。

那么eval和ast.literal_val()的区别是什么呢?

eval在做计算前并不知道需要转化的内容是不是合法的(安全的)python数据类型。只是在调用函数的时候去计算。如果被计算的内容不是合法的python类型就会抛出异常。

ast.literal则会判断需要计算的内容计算后是不是合法的python类型,如果是则进行运算,否则就不进行运算。


------------------------------引用自stackoverflow--------------------------------

datamap = eval(raw_input('Provide some data here: ') means that you actually evaluate the code before you deem it to be unsafe or not. It evaluates the code as soon as the function is called. See also the dangers of eval.

ast.literal_eval raises an exception if the input isn't a valid Python datatype, so the code won't be executed if it's not.

Use ast.literal_eval whenever you need eval. If you have Python expressions as an input that you want to evaluate, you shouldn't (have them).

shareedit

版权声明:本文为博主原创文章,未经博主允许不得转载。

转载于:https://www.cnblogs.com/yisuowushinian/p/4715601.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!