Users of namedtuple: do you use the _source attribute?

Steve D'Aprano steve+python at pearwood.info
Mon Jul 17 12:57:50 EDT 2017


collections.namedtuple generates a new class using exec, and records the source
code for the class as a _source attribute.

Although it has a leading underscore, it is actually a public attribute. The
leading underscore distinguishes it from a named field potentially
called "source", e.g. namedtuple("klass", ['source', 'destination']).


There is some discussion on Python-Dev about:

- changing the way the namedtuple class is generated which may
  change the _source attribute

- or even dropping it altogether

in order to speed up namedtuple and reduce Python's startup time.


Is there anyone here who uses the namedtuple _source attribute?

My own tests suggest that changing from the current implementation to one
similar to this recipe here:

https://code.activestate.com/recipes/578918-yet-another-namedtuple/

which only uses exec to generate the __new__ method, not the entire class, has
the potential to speed up namedtuple by a factor of four.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list