Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 791
cmcginty Avatar asked Jul 21 '09 23:07

cmcginty


People also ask

What is the point of name mangling?

Name mangling is the encoding of function and variable names into unique names so that linkers can separate common names in the language. Type names may also be mangled. Name mangling is commonly used to facilitate the overloading feature and visibility within different scopes.

What is name mangling in Java?

Name mangling is a term that denotes the process of mapping a name that is valid in a particular programming language to a name that is valid in the CORBA Interface Definition Language (IDL).

What are the ways to stop name mangling in C ++?

dllexport of a C++ function will expose the function with C++ name mangling. To disable name mangling either use a . def file (EXPORTS keyword) or declare the function as extern “C”.

What is private data field in Python?

When we declare data member as private it means they are accessible only side the class and are inaccessible outside the class. The technique of making a variable or method private is called data mangling.


2 Answers

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.

like image 59
RichieHindle Avatar answered Sep 28 '22 00:09

RichieHindle


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)

like image 33
too much php Avatar answered Sep 28 '22 00:09

too much php