【问题标题】:Usage of eval, exec, and ast.literal_eval [closed]eval、exec 和 ast.literal_eval 的使用 [关闭]
【发布时间】:2019-10-21 22:52:29
【问题描述】:

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

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

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

【问题讨论】:

标签: python exec eval


【解决方案1】:

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(或其他容器)时,动态创建一堆变量。

【讨论】:

  • 注意,过去基本上整个类定义都是动态执行的,但这减慢了速度,以至于添加了一个新的实现,使用exec只定义__new__
猜你喜欢
  • 2013-02-18
  • 1970-01-01
  • 1970-01-01
  • 2020-09-07
  • 2017-04-01
  • 2021-08-08
  • 1970-01-01
相关资源
最近更新 更多