Name-mangling is a lexical substitution mechanism in Python where the parser automatically alters any identifier within a class definition that begins with at least two leading underscores (Documentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
__) and has no more than one trailing underscore. This transformation occurs at compile time and applies to any matching identifier in the class scope, including instance attributes, methods, local variables, global declarations, nested classes, and imported module names.
The primary purpose of name-mangling is to prevent accidental name collisions. By prefixing the identifier with the class name, Python ensures that subclasses do not inadvertently override or shadow the internal identifiers of their parent classes when defining their own attributes or methods.
The Mangling Rule
When the Python parser encounters a matching identifier within aclass block, it rewrites the identifier according to the following pattern:
_: A single leading underscore.<ClassName>: The name of the enclosing class, with any leading underscores stripped.__<identifier_name>: The original identifier name, including its double underscores.
Syntax Visualization
Because mangling is a purely lexical operation performed by the parser, it affects all matching tokens within the class body, regardless of their programmatic role.Accessing Mangled Identifiers
Name-mangling is a text-substitution operation rather than a strict memory-protection mechanism (likeprivate in C++ or Java). The identifier remains fully accessible from outside the class if the mangled name is explicitly invoked.
Lexical Edge Cases
- Dunder Identifiers: Identifiers that both begin and end with double underscores (e.g.,
__init__,__dict__) are strictly exempt from name-mangling. - Class Name Stripping: If the class name itself begins with an underscore, those leading underscores are stripped during the mangling process. For example, the identifier
__valueinsideclass _Hidden:becomes_Hidden__value, not__Hidden__value. - Scope Limitation: Name-mangling only occurs within the lexical scope of a
classdefinition. Variables defined with double underscores at the module level or inside standalone functions are not mangled. - String Evaluation: Functions like
getattr(),setattr(), orhasattr()evaluate strings at runtime, bypassing the compile-time parser. They do not automatically mangle strings. You must pass the fully mangled string (e.g.,getattr(obj, "_ClassName__attr")) to interact with the attribute dynamically.
Master Python with Deep Grasping Methodology!Learn More





