[docs] [issue12086] Tutorial doesn't discourage name mangling

Radomir Dopieralski report at bugs.python.org
Mon May 16 10:35:44 CEST 2011

New submission from Radomir Dopieralski <python-bugs at sheep.art.pl>:

In the tutorial, at http://docs.python.org/tutorial/classes.html#private-variables you can read:

9.6. Private Variables
“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.

Note that the mangling rules are designed mostly to avoid accidents; it still is possible to access or modify a variable that is considered private. This can even be useful in special circumstances, such as in the debugger.


I think that this section doesn't stress enough how special the "__foo" syntax is and how rarely it should be used. If I was a programmer coming from Java to Python, I would start using "__foo" everywhere after reading this. I actually receive code written like that from programmers new to Python, and they point to that section of documentation when I ask why they did it.

At minimum, I'd add a paragraph that warns about how name mangling makes the code hard to reuse, difficult to test and unpleasant to debug.

assignee: docs at python
components: Documentation
messages: 136072
nosy: docs at python, sheep
priority: normal
severity: normal
status: open
title: Tutorial doesn't discourage name mangling
type: feature request
versions: Python 2.7

Python tracker <report at bugs.python.org>

More information about the docs mailing list