Users of namedtuple: do you use the _source attribute?

Steve D'Aprano steve+python at pearwood.info
Tue Jul 18 08:51:36 EDT 2017


On Tue, 18 Jul 2017 03:58 pm, Terry Reedy wrote:

>> On Monday, July 17, 2017 at 12:20:04 PM UTC-5, Steve D'Aprano wrote:
>>> 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']).

[...]

> Yes, No.  The developers of the class agree that a trailing underscore
> convention would have been better.  'source_' etc.


I actually disagree with Raymond, and I think his first instinct was the correct
one.

"source_" is already a public name, which means that users could want to create
fields with that name for some reason, just as they could create "source_code"
or "source_be_with_you" or any other name containing underscores. There is no
restriction on names ending in an underscore, and we have a convention to use
such names when they would otherwise clash with a keyword, e.g. "class_".

So I don't think that namedtuple should reserve names ending with underscore for
its own use. I think that Raymond's first decision was correct, and documenting
_source as public is the least-worst option.





[1] Maybe if we borrowed the keys to Guido's Time Machine and went back to
Python 0.9 we could argue that there should be. "Dunder names and names ending
in a single underscore are reserved for Python." But that would clash 

-- 
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