Users of namedtuple: do you use the _source attribute?

Michele Simionato michele.simionato at gmail.com
Mon Jul 17 23:56:41 EDT 2017


Il giorno lunedì 17 luglio 2017 19:20:04 UTC+2, Steve D'Aprano ha scritto:
> 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.

It is an attribute that looks handy for understanding how a namedtuple works, and can be used in debugging, but in practice I have never used it in production code. I use a a lot of namedtuple, and if we can get a factor 4 speedup I am pretty happy to lose _source.



More information about the Python-list mailing list