Sub topic 4
Double Underscore and Name Mangling
This chapter assumes you can define classes and methods, set instance attributes in __init__, and use inheritance with super(). The previous chapters covered the single underscore convention. Here you will see what happens when an attribute name starts with two underscores, why Python does this, and why it is often not the tool people expect it to be.
What name mangling is
Python has no enforced private attributes. A single leading underscore is only a signal to other programmers. A name that starts with two underscores, such as __balance, gets different treatment. Inside a class body, the compiler rewrites it to _ClassName__balance. This rewriting is called name mangling.
class Account:
def __init__(self):
self.__balance = 0
a = Account()
print(a._Account__balance) # 0
try:
a.__balance
except AttributeError:
print("no attribute named __balance")Inside __init__, the code self.__balance = 0 is compiled as if you had written self._Account__balance = 0. Outside the class, a.__balance is not rewritten, so Python looks for an attribute literally called __balance and fails. The mangled name still works, which shows that mangling is not real privacy.
You can see the mangled name by inspecting the instance:
class Account:
def __init__(self):
self.__balance = 0
print(vars(Account())) # {'_Account__balance': 0}The exact rules
Mangling follows a small set of rules. Knowing them removes most of the surprises.
| Name | Mangled? | Reason |
|---|---|---|
| `__balance` | Yes, to `_Account__balance` | Starts with two underscores and does not end with two |
| `__helper` (a method) | Yes, to `_Account__helper` | Methods and class variables are mangled too |
| `__init__` | No | Ends with two underscores, so it is a special ("dunder") name |
| `_balance` | No | A single underscore is only a convention |
| `balance__` | No | Does not start with two underscores |
Further details:
- The rewrite is
_plus the class name with its leading underscores removed, plus the original name. A class called_Hiddenproduces names like_Hidden__x, not__Hidden__x. - Mangling is textual and happens at compile time. It only affects identifiers written inside the class body. It does not touch string contents, so
getattr(a, "__balance")looks for a literal__balanceand fails. - Mangling applies to every identifier in the class body that matches the pattern, not only
self.attributes. That includes method names, class variables, and parameter names. - Code outside the class is never rewritten. Assigning
a.__balance = 99at module level creates a second, unrelated attribute.
class Account:
def __init__(self):
self.__balance = 0
a = Account()
a.__balance = 99 # outside the class: no mangling
print(vars(a)) # {'_Account__balance': 0, '__balance': 99}This is a common source of silent bugs. The assignment succeeds, but it does not change the value the class uses.
Why it exists: avoiding subclass collisions
Name mangling was not designed as a security feature. Its purpose is to stop a subclass from accidentally overwriting an attribute that a parent class uses internally. Without it, two classes in one hierarchy can pick the same name for different purposes.
class Base:
def __init__(self):
self.__id = "base"
def base_id(self):
return self.__id
class Child(Base):
def __init__(self):
super().__init__()
self.__id = "child"
def child_id(self):
return self.__id
c = Child()
print(c.base_id()) # base
print(c.child_id()) # child
print(sorted(vars(c))) # ['_Base__id', '_Child__id']Each class gets its own slot, _Base__id and _Child__id, so the two do not interfere. If both had used _id, the child's assignment would have replaced the parent's value, and base_id() would have returned "child".
The same applies to methods. A mangled method cannot be overridden by accident, which also means a subclass cannot override it on purpose.
class Report:
def build(self):
return self.__header() + "body"
def __header(self):
return "H:"
class Fancy(Report):
def __header(self):
return "FANCY:"
print(Fancy().build()) # H:bodyReport.build calls self._Report__header(). The subclass defined _Fancy__header, which build never calls. If you want subclasses to customize a step, use a single underscore or a normal name instead.
Mangling is not privacy
Beginners often use double underscores to make attributes "really private". This does not work, for three reasons.
- Anyone can read or write
obj._Account__balance. The name is predictable. - Mangling gets in the way of debugging, testing, and tools that inspect attributes. You see
_Account__balanceinvars()and in tracebacks. - It couples the attribute name to the class name. If you rename
Account, the stored attribute names change. This matters for code that reads__dict__, and for pickled objects that were saved under the old names.
Python's guidance is to use a single underscore for "internal, do not touch" and to rely on properties when you need to control access. Reach for double underscores only when you are writing a class that others will subclass, and you have an internal attribute whose name might plausibly clash with a subclass's.
Interaction with properties
Properties and mangling combine without trouble, but you must be consistent about which name you use. A property stores its value in a backing attribute. If that attribute uses a double underscore, only code inside the same class can reach it by the short name.
class Celsius:
def __init__(self, degrees):
self.degrees = degrees
@property
def degrees(self):
return self.__degrees
@degrees.setter
def degrees(self, value):
if value < -273.15:
raise ValueError("temperature is below absolute zero")
self.__degrees = value
class Kelvin(Celsius):
@property
def kelvin(self):
# self.__degrees here would mean self._Kelvin__degrees,
# which does not exist. Go through the property instead.
return self.degrees + 273.15
k = Kelvin(25)
print(k.kelvin) # 298.15The comment in Kelvin.kelvin points at the trap. Inside Kelvin, the name self.__degrees is rewritten with Kelvin's name, so it would raise AttributeError. The property degrees is the right way in, because the property's code lives in Celsius and is mangled with Celsius's name. With a single underscore (_degrees), the subclass could read the backing attribute directly. That is one reason single underscore is the usual choice for property storage.
Common errors
- Reading a mangled name from a subclass. A subclass cannot use
self.__xto read a parent's__x. Use a property, a method, or the full mangled name. - Assigning from outside the class.
obj.__x = 1creates a new attribute named__xand does not change_Class__x. - Using strings with
getattrorsetattr. Strings are not mangled. Pass"_Account__balance"if you must, or better, avoid dynamic access to such names. - Expecting dunder-style names to be mangled. Names such as
__version__are left alone, so they are safe to use as special names. - Renaming a class and breaking stored data. Serialized objects that contain mangled keys no longer match after a rename.
Decision criteria
| Situation | Use |
|---|---|
| Attribute is internal to the class, subclasses may use it | `_name` |
| Attribute is internal and a subclass could plausibly reuse the same name | `__name` |
| Attribute needs validation or computed behavior | `@property` with a `_name` backing attribute |
| You want to forbid access | Not possible in Python. Document it instead. |
Exercise
A class Stack stores its items in self.__items. A user writes s = Stack(); s.__items = [1, 2, 3] at module level and then calls s.push(4), which appends to self.__items inside the class. What does vars(s) show, and which list did push change?
Show answer
vars(s) shows two keys: _Stack__items, which holds the list that __init__ created and that push changed, and __items, which holds [1, 2, 3]. The module-level assignment is not mangled, so it created a separate attribute. Inside the class, self.__items is rewritten to self._Stack__items, so push modified only the original list.
Exercise
Why does Fancy().build() print H:body in the Report example, even though Fancy defines its own __header?
Show answer
Inside Report, the call self.__header() is compiled to self._Report__header(). The subclass method is stored as _Fancy__header, a different name, so it does not replace the parent's method and build never calls it.