Why doesn't the namedtuple module use a metaclass to create nt class objects?

后端 未结 4 1718
野性不改
野性不改 2021-02-18 14:02

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

4条回答
  •  醉话见心
    2021-02-18 14:54

    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:

    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

    Additionally, here is the part of the description of 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.

    If you're looking for some alternative implementations:

    • abstract base class + mix-in for named tuples recipe by Jan Kaliszewski

    • metaclass-based implementation by Aaron Iles (see his blog post)

提交回复
热议问题