Python Encapsulation: Name Mangling and Properties
Understand Python encapsulation through name mangling and properties, with practical code examples, comparison, and tradeoffs for production class design.

Python encapsulation is not enforced by the language the way it is in Java or C#. There is no private keyword that prevents external access at compile time. Instead, encapsulation in Python relies on conventions and a few language mechanisms that discourage direct access to internal state. Understanding these mechanisms is essential for writing maintainable classes that protect their invariants without fighting the language's design.
What Encapsulation Means in Python
Encapsulation bundles data with the methods that operate on that data and restricts direct access to an object's internal representation. In Python, the community convention is to prefix an attribute with a single underscore (_name) to signal that it is protected and not part of the public API. This is a strong hint, not a barrier. External code can still read and write _name without any error. The double underscore (__name) triggers name mangling: the name is rewritten in the compiled class body to _ClassName__name. That makes accidental access less likely but does not make it impossible.
The practical goal of encapsulation in Python is to prevent external code from putting an object into an invalid state. For example, if a BankAccount class has a balance attribute, you want to ensure that it never becomes negative. Direct attribute assignment would allow account.balance = -100. Encapsulation gives you a place to enforce that rule.
Name Mangling with Double Underscores
When you write self.__balance inside a class, Python rewrites the attribute name to _ClassName__balance. This is called name mangling. It is primarily intended to avoid name collisions in subclasses, not to provide strong privacy. Consider this example:
class BankAccount:
def __init__(self, initial_balance):
self.__balance = initial_balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit amount must be positive")
self.__balance += amount
def get_balance(self):
return self.__balanceExternal code that tries account.__balance will raise an AttributeError because the attribute is stored as _BankAccount__balance. You can still access it directly if you know the mangled name: account._BankAccount__balance = -100. Name mangling is a deterrent, not a security boundary. It is most useful in large codebases or libraries where a subclass might accidentally override an internal attribute with the same name.
Using Properties for Controlled Access
The idiomatic way to implement encapsulation in Python is with the @property decorator. Properties allow you to define methods that behave like attributes, so you can add validation, logging, or computed values without changing the public interface. The same BankAccount class can be written as:
class BankAccount:
def __init__(self, initial_balance):
self.balance = initial_balance
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
if value < 0:
raise ValueError("Balance cannot be negative")
self._balance = value
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit amount must be positive")
self._balance += amountNow account.balance = -100 raises a ValueError, and BankAccount(-100) also raises one because __init__ assigns through the property. account.balance returns the current value. The underlying attribute is still accessible as _balance, but the property provides a controlled interface. This pattern is more explicit than name mangling and is the recommended approach for most production code. Properties also support a deleter, which you can use to define cleanup behavior when del account.balance is called.
Comparing Name Mangling and Properties
Both mechanisms serve different purposes. Name mangling prevents accidental attribute collisions in inheritance hierarchies, while properties give you full control over attribute access. The following table summarizes the key differences:
| Criterion | Name Mangling (__attr) | Properties (@property) |
|---|---|---|
| Primary purpose | Avoid name collisions in subclasses | Control attribute access and validation |
| Access restriction | Deters accidental external access | Enforces rules via setter logic |
| Inheritance behavior | Mangled name is class-specific | Inherited and can be overridden |
| Runtime overhead | No runtime call; rewriting happens at compile time | Function call overhead on access |
| Debugging | Mangled names appear in stack traces | Clean attribute names in tracebacks |
| Recommended use | Internal helpers, mixins | Public API with invariants |
In practice, you rarely need name mangling for encapsulation. If you want to protect an invariant, use a property. If you are writing a base class and want to avoid a subclass accidentally overriding an internal method or attribute, name mangling can be useful. Many Python libraries use single underscores for internal state and reserve double underscores for cases where subclass collisions are a real risk.
Encapsulation in Inheritance and Overriding
When a subclass inherits from a class that uses name mangling, the mangled name is based on the class where the attribute is defined. For example, if SavingsAccount inherits from BankAccount, the __balance defined in BankAccount becomes _BankAccount__balance even when accessed from a SavingsAccount instance. This means a subclass cannot accidentally overwrite that attribute by defining its own __balance. Properties, on the other hand, are inherited normally. A subclass can override the getter or setter to extend or modify behavior. This flexibility is often desirable, but it also means that a subclass can bypass the parent's validation if it overrides the setter carelessly. When designing a class hierarchy, decide whether the encapsulation boundary should be rigid (name mangling) or extensible (properties).
Runtime Cost and Maintainability
Properties add a small runtime cost because every access goes through a method call. In tight loops or performance-critical code, this overhead can become measurable, though it is rarely significant compared to I/O or network operations. If you need raw performance and your class does not have invariants to enforce, use a plain attribute. However, if you add a property later, existing code that assigns to that attribute will now run the setter; assignments that violate the new validation will fail. Renaming the public attribute instead is what breaks callers. This is why it is often wise to start with a simple attribute and add a property only when validation is required. Name mangling has almost no runtime overhead because it is resolved at compile time, but it makes debugging harder: the mangled name appears in tracebacks and debuggers, which can confuse developers who are not familiar with the pattern.
Maintainability also depends on how you document your intent. Single underscore is a strong signal to other developers that an attribute is internal. If you use double underscores, be aware that it can surprise developers who try to access the attribute from a subclass or from external code. The Python community generally prefers a single underscore plus a property for encapsulation, reserving double underscores for specific collision-avoidance scenarios.
Common Pitfalls and Practical Guidance
One common mistake is using name mangling as a privacy mechanism and then being surprised that the attribute is still accessible via the mangled name. Another is overusing properties for trivial attributes that do not need validation, which adds boilerplate without real benefit. A more subtle issue is relying on name mangling in multiple-inheritance hierarchies: because the mangled name is tied to the class where it appears, mixins and subclasses can resolve attributes in ways that are hard to predict. When in doubt, follow these guidelines:
- Use a single underscore for internal state that is not part of the public API.
- Use
@propertywhen you need to enforce an invariant or compute a value dynamically. - Use double underscores only when you have a concrete risk of subclass attribute collisions.
- Document the intended usage of each attribute in the class docstring.
Encapsulation in Python is a design discipline, not a language-enforced rule. The tools you choose should match the level of control your application requires. For most business logic, properties provide the right balance of safety and flexibility. For low-level infrastructure code where performance and collision avoidance matter, name mangling may be the better fit. Understanding the tradeoffs lets you write classes that are robust, maintainable, and idiomatic.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.