name mangling

In Python, name mangling is a mechanism that protects class and instance attributes from being accidentally overridden or accessed from outside the class.

Python does name mangling automatically when you prefix an attribute name with two underscores (__). When an attribute begins with __, Python changes the name of the attribute by adding an underscore and the class name to the beginning of the attribute name. For example, .__name in a Robot class becomes ._Robot__name.

Name mangling makes it more challenging for subclasses or external code to access or modify these attributes. However, it doesn’t make it impossible. You can still access mangled names if you know the mangling pattern, but doing so is generally discouraged as it breaks the encapsulation principle.

Example

Here’s a quick example demonstrating name mangling:

Python
>>> class Robot:
...     def __init__(self, name):
...         self.__name = name
...     def get_name(self):
...         return f"My name is {self.__name}"
...

>>> robot = Robot("Wall-e")
>>> robot.get_name()
'My name is Wall-e'

>>> # Attempt to access the mangled name directly
>>> robot.__name
Traceback (most recent call last):
    ...
AttributeError: 'Robot' object has no attribute '__name'

>>> # Access the mangled name
>>> robot._Robot__name
'Wall-e'

In this example, when you attempt to access robot.__name directly, you get an AttributeError because Python has changed its name to _Robot__name.

Tutorial

Single and Double Underscores in Python Names

In this tutorial, you'll learn a few Python naming conventions involving single and double underscores (_). You'll learn how to use this character to differentiate between public and non-public names in APIs, write safe classes for subclassing purposes, avoid name clashes, and more.

intermediate best-practices python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated March 6, 2025 • Reviewed by Martin Breuss