我花了一些时间调查 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.
如果您正在寻找一些替代实现:
abstract base class + mix-in for named tuples Jan Kaliszewski 的食谱
metaclass-based implementation作者:Aaron Iles(见他的 blog post)
关于python - 为什么 namedtuple 模块不使用元类来创建 nt 类对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28184531/