Python Coding Standards – Should Private Methods Always Use Underscore Prefix in Python?

code-qualitycoding-standardsencapsulationinheritancepython

Prefixing methods and members with an underscore indicates internal use. For simple classes, I sometimes find the easier reading and typing of self.foo outweighing the indent of self._foo. Especially when implementing an abstract interface, this interface is already pretty clear. Of course, the class could have more public members and methods that it wants to provide. Should I always use the leading underscore if something does not need to be publicly accessible?

Best Answer

According to the Classes section of the Python docs:

“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.

_something indicates to others that something isn't part of the API and can/will be changed without notice, ie should be treated as internal/private.

If you are using inheritance, then __something is a better choice as it both indicates it's an implementation detail and avoids name conflicts with subclasses.