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

boB Stepp robertvstepp at gmail.com
Tue Jun 2 19:12:04 EDT 2020


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.

-- 
Wishing you only the best,

boB Stepp


More information about the Tutor mailing list