为什么namedtuple模块不使用元类来创建nt类对象? [英] Why doesn't the namedtuple module use a metaclass to create nt class objects?

查看:84
本文介绍了为什么namedtuple模块不使用元类来创建nt类对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了一些时间研究 collections.namedtuple模块几个星期前.该模块使用一个工厂函数,该函数将动态数据(新的namedtuple类的名称以及类的属性名称)填充为一个很大的字符串.然后以字符串(代表代码)作为参数执行exec,并返回新类.

I spent some time investigating the collections.namedtuple module a few weeks ago. The module uses a factory function which populates the dynamic data (the name of the new namedtuple class, and the class attribute names) into a very large string. Then exec is executed with the string (which represents the code) as the argument, and the new class is returned.

当针对这种事情有特定的工具(即元类)可以使用时,有人知道为什么要这样做吗?我没有尝试自己做,但是看来namedtuple模块中发生的所有事情都可以使用namedtuple元类轻松完成,例如:

Does anyone know why it was done this way, when there is a specific tool for this kind of thing readily available, i.e. the metaclass? I haven't tried to do it myself, but it seems like everything that is happening in the namedtuple module could have been easily accomplished using a namedtuple metaclass, like so:

class namedtuple(type):

推荐答案

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

There are some hints in the issue 3974. The author proposed a new way to create named tuples, which was rejected with the following comments:

原始版本的好处似乎在于它更快, 多亏了对关键方法进行硬编码. -安东尼·皮特鲁(Antoine Pitrou)

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

使用exec并没有什么邪恶的.较早版本使用其他 的方法,它们被证明是不必要的复杂,并且出乎意料 问题.这是命名元组的一个关键功能,即它们确实是 相当于一个手写的课程.-Raymond Hettinger

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

此外,这是原始namedtuple食谱的描述的一部分:

Additionally, here is the part of the description of the original namedtuple recipe:

...配方已演变为目前的执行风格,在此我们可以 免费的Python高速内置参数检查.新的 建立和执行模板的风格使__new__和 __repr__的功能比本食谱的早期版本更快,更干净.

... 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.

如果您正在寻找其他替代实施方式:

If you're looking for some alternative implementations:

基于元类的实现(请参见他的 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆