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.
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.
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).
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”.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With