[Tutor] Named tuple special methods and attributes start with an underscore?
Cameron Simpson
cs at cskk.id.au
Wed Jun 3 01:55:59 EDT 2020
On 02Jun2020 21:04, boB Stepp <robertvstepp at gmail.com> wrote:
>On Wed, Jun 03, 2020 at 11:23:04AM +1000, Cameron Simpson wrote:
>>By using leading underscores, the user of nametuple is free to use any
>>field names they like as long as they avoid underscores. Don't forget
>>that you can subclass a namedtuple, too. I've got several classes
>>which look like this:
>>
>> class Something(namedtuple('Something', 'a b c')):
>> def some_method(...): ...
>>
>>You're saying I shouldn't be able to have a method called "replace"
>>on my arbitrary class?
>
>Then why not str._replace() instead of the current str.replace()?
Because str is a class with many methods and well defined semantics.
namedtuple is essentially an efficient skeleton for a tuple with some
fixed field names, and initially _no_ semantics/methods. It is basicly a
bare container. Whereas str is a thing with a purpose.
>Is it
>thought that users are less likely to want to modify the string class? Is
>this the design criteria -- the likeliness of user subclassing?
It is more that a namedtuple is very basic and has no particular
behaviours, maybe like object or SimpleNamespace, etc. It goes out of
its way to _not_ pollute the public space with the (small) number of
presupplied methods.
There is a rule of thumb that one shouldn't subclass builtin types like
str, but that is not the criterion here: it is the purpose agnosticness
of namedtuple.
Let me make a different example. I've got a class which loads CSV or
Excel sheets and presumes the first row is a heading row. It reads this,
then constructures a namedtuple subclass whose fields are computed from
the header names (it does stuff like downcase them and turn whitespace
into underscores). Anyway, all the field names commence with letters and
might contain anything depending on the comparative sanity of the person
supplying the spreadsheet. This is only robust because there are no
nametuple starts-iwth-a-letter methods.
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Tutor
mailing list