Sub topic 4
Double underscore and name mangling
This chapter assumes you can define classes with __init__, know that a single leading underscore marks an attribute as internal by convention, and can catch exceptions such as AttributeError.
What name mangling does
A name that starts with two underscores and does not end with two underscores is rewritten by the compiler. Inside a class named Account, __balance becomes _Account__balance. The rewrite is _ClassName followed by the original name.
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")The attribute is stored under the mangled name. The lookup a.__balance is written outside the class, so it is not rewritten and finds nothing. The mangled name still works, because Python does not enforce privacy.
Correction: the diagram must use the required fence. Here it is.
Why it exists
Mangling is not a security feature. Its purpose is to stop a subclass from accidentally overwriting an attribute that a parent class relies on. Each class gets its own version of the name.
class Base:
def __init__(self):
self.__token = "base"
def base_token(self):
return self.__token
class Child(Base):
def __init__(self):
super().__init__()
self.__token = "child"
c = Child()
print(c.base_token()) # base
print(c.__dict__) # {'_Base__token': 'base', '_Child__token': 'child'}With a single underscore, Child would have replaced the parent's _token, and base_token() would have returned "child". Here the two attributes live side by side.
Rules and gotchas
- Mangling happens at compile time and only to names written in the class body, including its methods. Strings are not touched, so
getattr(a, "__balance")fails. You needgetattr(a, "_Account__balance"). - Names that end with two underscores, such as
__init__and__len__, are never mangled. - Leading underscores on the class name are stripped when building the prefix. A class named
_Hiddenmangles__xto_Hidden__x. - Code outside any class that uses
obj.__xis not mangled. The same line inside a class body is mangled with that class's name, which can cause a surprisingAttributeError. - Renaming a class changes its mangled names, which breaks code that depends on them, including pickled data.
When to use it
Most Python code does not need double underscores. Use a single underscore to signal that an attribute is internal, and use @property when you need control over access. Reserve double underscores for classes that are designed to be subclassed by people you do not control, where a collision on a helper attribute would be hard to debug. Using it only to "hide" data gives a false sense of safety, because the mangled name is one line away.
Exercise
A class Wallet stores self.__cash = 10. From outside the class, getattr(w, "__cash") raises AttributeError for a Wallet instance w. What call returns 10, and why does the original call fail?
Show answer
getattr(w, "_Wallet__cash") returns 10. The compiler mangles __cash only where it appears as a name in the class body, and the stored attribute is _Wallet__cash. A string passed to getattr is never rewritten, so the lookup for "__cash" finds nothing.