eval、exec 和 ast.literal_eval 的用法

Usage of eval, exec, and ast.literal_eval

evalexecast.literal_eval有实际用途吗?我在实际使用中看到它们的唯一次数是将 python 对象之类的东西保存到文件中并且没有腌制或其他任何东西。

使用这些函数的一些实际的重要用例是什么?我在文档中找到的唯一示例是:

>>> x = 1
>>> eval('x+1')
2

evalexec 用于动态执行简单的 Python 表达式或更复杂的语句(分别)。

So, one practical example from the standard library, collections.namedtuple uses exec to dynamically define a __new__ method for the tuple subclass being returned:

# 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

这有时是有道理的,但是,这经常被没有经验的程序员滥用来编写不必要的动态代码,例如动态创建一堆变量,而它们本应使用 listdict(或其他容器)。