What is the benefit of private name mangling?

Python provides private name mangling for class methods and attributes.

Are there any concrete cases where this feature is required, or is it just a carry over from Java and C++?

Please describe a use case where Python name mangling should be used, if any?

Also, I'm not interested in the case where the author is merely trying to prevent accidental external attribute access. I believe this use case is not aligned with the Python programming model.


Solution 1:

It's partly to prevent accidental internal attribute access. Here's an example:

In your code, which is a library:

class YourClass:
    def __init__(self):
        self.__thing = 1           # Your private member, not part of your API

In my code, in which I'm inheriting from your library class:

class MyClass(YourClass):
    def __init__(self):
        # ...
        self.__thing = "My thing"  # My private member; the name is a coincidence

Without private name mangling, my accidental reuse of your name would break your library.

Solution 2:

From PEP 8:

If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores. This invokes Python's name mangling algorithm, where the name of the class is mangled into the attribute name. This helps avoid attribute name collisions should subclasses inadvertently contain attributes with the same name.

(Emphasis added)