pythonではeval()とastを使用します.literal_eval()の区別分類:...

1270 ワード

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).
share
edit
edited 
Mar 4 '13 at 8:59
answered 
Mar 4 '13 at 8:52
Volatility
13.4k
3
26
53
add a comment
本文はブロガーのオリジナル文章で、ブロガーの許可を得ずに転載してはならない.
転載先:https://www.cnblogs.com/yisuowushinian/p/4715601.html