bpo-28638: speed up namedtuple creation by avoiding exec by JelleZijlstra · Pull Request #2736 · python/cpython (original) (raw)

Creating a namedtuple is relatively slow because it uses exec().
This commit reduces the exec()'ed code, but still uses exec() for
creating the __new__ method. I don't know of a way to avoid using
exec() for __new__ beyond manipulating bytecode directly.

However, avoiding exec() for creating the class itself still yields
a significant speedup. In an unscientific benchmark I ran, creating
1000 namedtuple classes now takes about 0.14 s instead of 0.44 s.

There is one backward compatibility break: namedtuples no longer have
a _source attribute, because we no longer exec() their source. I kept
the verbose=True argument around for compatibility, but it now does
nothing.

cc @sixolet @methane

https://bugs.python.org/issue28638