liveBook · Manning

Name mangling

As explained in Software Design for Python Programmers

Python name mangling is the transformation of double-underscore class attribute names to include the defining class name.

Name mangling transforms a class attribute with two leading underscores by incorporating the defining class name. Use it when a class may be subclassed and an attribute should not be accessed by subclasses, helping prevent accidental name collisions. section 2.3.1

Protecting catalogue state

An initial Catalogue uses _booklist for its stored books. When subclasses are introduced, rename that attribute to __booklist to discourage subclass access; Python then mangles the name with Catalogue. The single-underscore _is_match() method remains non-public by convention. section 2.3.1

How Software Design for Python Programmers covers it

How deep it goes
Defines the transformation and design rationale, but does not show the mangled spelling or its runtime internals.
Examples
Uses Catalogue.__booklist as the protected-subclass example, contrasting it with Book and Catalogue single-underscore members.
What you can do after
Evaluate when double leading underscores reduce accidental attribute collisions during subclass design.
How it connects
Connects name mangling with inheritance, subclasses, non-public members, and Python naming conventions.

Also explained in

Compare how 3 books explain name mangling →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Software Design for Python Programmers. The section links point to the parts of the book it draws on.