What is the benefit of private name mangling? What is the benefit of private name mangling? python python

What is the benefit of private name mangling?


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.


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)


All previous answers are correct but here is another reason with an example. Name Mangling is needed in python because to avoid problems that could be caused by overriding attributes. In other words, in order to override, the Python interpreter has to be able to build distinct id for child method versus parent method and using __ (double underscore) enable python to do this. In below example, without __help this code would not work.

class Parent:    def __init__(self):       self.__help("will take child to school")    def help(self, activities):        print("parent",activities)    __help = help   # private copy of original help() methodclass Child(Parent):    def help(self, activities, days):   # notice this has 3 arguments and overrides the Parent.help()        self.activities = activities        self.days = days        print ("child will do",self.activities, self.days)# the goal was to extend and override the Parent class to list the child activities tooprint ("list parent & child responsibilities")c = Child()c.help("laundry","Saturdays")