eval、exec 和 ast.literal_eval 的用法
Usage of eval, exec, and ast.literal_eval
eval
、exec
、ast.literal_eval
有实际用途吗?我在实际使用中看到它们的唯一次数是将 python 对象之类的东西保存到文件中并且没有腌制或其他任何东西。
使用这些函数的一些实际的重要用例是什么?我在文档中找到的唯一示例是:
>>> x = 1
>>> eval('x+1')
2
eval
和 exec
用于动态执行简单的 Python 表达式或更复杂的语句(分别)。
# Create all the named tuple methods to be added to the class namespace
s = f'def __new__(_cls, {arg_list}): return _tuple_new(_cls, ({arg_list}))'
namespace = {'_tuple_new': tuple_new, '__name__': f'namedtuple_{typename}'}
# Note: exec() has the side-effect of interning the field names
exec(s, namespace)
__new__ = namespace['__new__']
__new__.__doc__ = f'Create new instance of {typename}({arg_list})'
if defaults is not None:
__new__.__defaults__ = defaults
这有时是有道理的,但是,这经常被没有经验的程序员滥用来编写不必要的动态代码,例如动态创建一堆变量,而它们本应使用 list
或 dict
(或其他容器)。
eval
、exec
、ast.literal_eval
有实际用途吗?我在实际使用中看到它们的唯一次数是将 python 对象之类的东西保存到文件中并且没有腌制或其他任何东西。
使用这些函数的一些实际的重要用例是什么?我在文档中找到的唯一示例是:
>>> x = 1 >>> eval('x+1') 2
eval
和 exec
用于动态执行简单的 Python 表达式或更复杂的语句(分别)。
# Create all the named tuple methods to be added to the class namespace
s = f'def __new__(_cls, {arg_list}): return _tuple_new(_cls, ({arg_list}))'
namespace = {'_tuple_new': tuple_new, '__name__': f'namedtuple_{typename}'}
# Note: exec() has the side-effect of interning the field names
exec(s, namespace)
__new__ = namespace['__new__']
__new__.__doc__ = f'Create new instance of {typename}({arg_list})'
if defaults is not None:
__new__.__defaults__ = defaults
这有时是有道理的,但是,这经常被没有经验的程序员滥用来编写不必要的动态代码,例如动态创建一堆变量,而它们本应使用 list
或 dict
(或其他容器)。