为什么要从字符串模板创建Python的namedtuple实例?

2024-04-25 01:27:52 发布

您现在位置:Python中文网/ 问答频道 /正文

当我阅读Python的collections模块(http://hg.python.org/cpython/file/2.7/Lib/collections.py#l234)的源代码时,我发现namedtuple函数从使用exec执行的字符串模板创建类的定义。为什么不简单地在函数中定义一个类,就像在编写装饰器时那样?在我看来,这将是一个更具可读性和更可靠的解决方案,不是吗?我敢打赌Python核心开发人员知道他们在做什么,那么我在这里遗漏了什么呢?你知道吗


Tags: 模块函数pyorghttp定义源代码lib
1条回答
网友
1楼 · 发布于 2024-04-25 01:27:52

雷蒙德·赫廷格在他的original ActiveState recipe中简短地提到了这一点:

Thanks to Peter Kovac pointing-out deficiencies in the keyword argument checking. Because of his comments, 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.

相关问题 更多 >