[Tutor] Named tuple special methods and attributes start with an underscore?

Cameron Simpson cs at cskk.id.au
Tue Jun 2 21:23:04 EDT 2020


On 02Jun2020 18:12, boB Stepp <robertvstepp at gmail.com> wrote:
>I was reading an article on the collections library
>(https://davidmuller.github.io/posts/2020/05/08/collections-module-Python3.html).
>In it it had the following note:  "In Python, methods with leading
>underscores are usually considered “private.” Additional methods provided
>by namedtuple (like _asdict(), ._make(), ._replace(), etc.), however, are
>public."  This greatly surprised me.  So I went to the Python docs
>(https://docs.python.org/3/library/collections.html#collections.namedtuple)
>and found:  "In addition to the methods inherited from tuples, named tuples
>support three additional methods and two attributes. To prevent conflicts
>with field names, the method and attribute names start with an underscore."
>Huh?!?
>
>The mentioned 5 items are:  _make, _asdict, _replace, _fields and
>_field_defaults.  Of the items "_replace" is the most surprising as that is
>already used by Python in other contexts such as str.replace().  These
>items don't look to be likely field names to be used by anyone.  Any
>illumination for this design decision?  To my (perhaps naive) eyes this
>strikes me as extraordinarily inconsistent Python syntax.

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?

The _foo thing is only a convention, through _normally_ strongly adhered 
to. You have the same kind of issue in any shared namespace, and by 
using _foo for a small number of special but documented methods we leave 
the way clear for _any_ starts-with-a-letter name to be a field or 
method of a namedtuple class or subclass.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list