Pergunta

While I was reading the source of Python's collections module (http://hg.python.org/cpython/file/2.7/Lib/collections.py#l234), I found that namedtuple function creates the definition of a class from a string template which is executed with exec. Why isn't it done by simply defining a class inside the function, like you do it when you write a decorator? It seems to me that it would be more readable and more reliable solution, wouldn't it? I bet Python core developers know what they do, so what am I missing here?

Foi útil?

Solução

Raymond Hettinger mentions this briefly in his 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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top