Python – Why is _replace Method of Namedtuple Classes Protected?

coding-styleinheritancepython

In the section Method Names and Instance Variables, the Python Style Guide (aka PEP 0008) says, "Use one leading underscore only for non-public methods and instance variables." Why then, does the _replace method on namedtuple have a leading underscore? namedtuple classes themselves do not invoke _replace at all, and meanwhile the existence of _replace is advertised in the docstring for namedtuple() (see here, for example).

Best Answer

namedtuple is a bit unusual thing in python. It is not a base class, it is a class generator. Invoking it creates a new class that uses a tuple for its storage and can be manipulated as either tuple or normal class with named fields.

The generated class is intended to be used as a base for your own types that will add methods, and constraints. Including constraints that tie the values of individual fields together.

So the namedtuple might be used as base for classes that don't support replacing. And since derived class can't remove methods its base provides, the method must not be public.

However some derived classes might want that functionality. So it is provided, as internal method. The subclass can export it if it has a good use for it.