python - 为什么 namedtuple 模块不使用元类来创建 nt 类对象?

标签 python metaclass python-internals namedtuple

我花了一些时间调查 collections.namedtuple module几周前。该模块使用工厂函数将动态数据(新的 namedtuple 类的名称和类属性名称)填充到一个非常大的字符串中。然后 exec 以字符串(代表代码)为参数执行,并返回新的类。

有谁知道为什么要这样做,当有一种现成的用于这种东西的特定工具时,即元类?我自己没有尝试过,但似乎 namedtuple 模块中发生的所有事情都可以使用 namedtuple 元类轻松完成,如下所示:

class namedtuple(type):

等等等等

编辑:谦虚地建议阅读the answer I wrote several years later ,在页面下方。

最佳答案

issue 3974 中有一些提示.作者提出了一种创建命名元组的新方法,但被拒绝并给出以下评论:

It seems the benefit of the original version is that it's faster, thanks to hardcoding critical methods. - Antoine Pitrou

There is nothing unholy about using exec. Earlier versions used other approaches and they proved unnecessarily complex and had unexpected problems. It is a key feature for named tuples that they are exactly equivalent to a hand-written class. - Raymond Hettinger

另外,这里是the original namedtuple recipe的描述部分:

... the recipe has evolved to its current exec-style where we get all of Python's high-speed builtin argument checking for free. The new style of building and exec-ing a template made both the __new__ and __repr__ functions faster and cleaner than in previous versions of this recipe.

如果您正在寻找一些替代实现:

关于python - 为什么 namedtuple 模块不使用元类来创建 nt 类对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28184531/

相关文章:

python - 避免每次都调用 __new__

Python:使用用户输入作为类名的类工厂

python - 写一个生成器还是返回一个生成器?

python - 使用列数组向量化 pandas 数据框列查找

python - 根据列的最大值删除 Pandas 数据框行

Python 替换函数

Python ABC 多重继承

python - 像 dict.fromkeys 这样的内置类型的函数描述符与普通方法的行为不同

python - 在导入的 __init__.py 中导入行为不同

python - 什么是 gevent.queue.Channel?