Name mangling in Python

Yasser Sinjab
1 min readJun 20, 2019

I was reading about why it is better to avoid using two leading underscores to create a private attribute in Python class. Then I found that Python use what is called “Name mangling” Well what was interesting is it is a compiler feature. Let’s read its definition in wikipedia:

In compiler construction, name mangling (also called name decoration) is a technique used to solve various problems caused by the need to resolve unique names for programming entities in many modern programming languages.

Programming entities could be any class, function, or any other datatypes.

Private and protected attributes in Python:

For many programmers who is coming from static language background: the first thing we are gonna look for in Python is: where are the access modifiers? :D

Well first Python is dynamic language, they handle stuff a little bit differently. Let’s take an example:

The point here is : if your concern is name clashes, use explicit name mangling instead of automatic name mangling (like: call it __The_Customer_first_name). Or use the underscore protected attribute and developers should respect the privacy of your attributes as they respect the CONSTANT_VARIABLE.

--

--

Yasser Sinjab

Software Engineer. Data nerd. Machine learning enthusiast.