Sub topic 3
Single underscore: signaling internal use
This chapter assumes you can define classes with __init__, set instance attributes, and import names from one module into another. You don't need properties yet. The chapter before this one covered what encapsulation means in Python. The chapters after it cover name mangling and @property.
The convention
Python has no private keyword. Instead, a name that starts with one underscore tells readers: "this is an implementation detail. Don't depend on it." [PEP 8](https://peps.python.org/pep-0008/) calls these names non-public. The convention applies to:
- instance attributes, such as
self._cache - methods, such as
def _validate(self) - module-level functions, classes, and variables
- whole modules, such as
_internal.py
The underscore is a promise from the author to the user. The author says the name may change or vanish in any release without notice. The user agrees not to rely on it. Names without an underscore are the public interface, which you are expected to keep stable.
What Python actually does with it
Almost nothing. The interpreter treats _items exactly like items.
class Cart:
def __init__(self):
self._prices = []
self._total = 0
def add(self, price):
self._prices.append(price)
self._total += price
def total(self):
return self._total
cart = Cart()
cart.add(10)
cart.add(5)
print(cart.total()) # 15
cart._prices.append(100) # allowed: Python does not stop you
print(cart.total()) # 15, the cached total is now stale
print(sum(cart._prices)) # 115The class keeps _total in step with _prices. That is the invariant, a condition the class must keep true. Code that reaches into _prices bypasses add() and breaks the invariant. The underscore warned against exactly this, but nothing enforced the warning. This is what "consenting adults" means in Python culture: the language trusts you, and you carry the responsibility.
The few places the underscore has an effect
The underscore changes behavior in a few places, all of them tooling or import behavior. None of it involves attribute access.
| Where | Effect |
|---|---|
| `from module import *` | Names starting with `_` are skipped, unless the module lists them in `__all__`. |
| Linters (for example pylint's `protected-access` check) | Code outside a class that touches `obj._name` gets a warning. |
| IDEs and shells | Autocomplete often hides or ranks underscore names lower. |
| Documentation tools (`pydoc`, Sphinx autodoc) | Underscore members are left out by default. |
The star-import rule is the only one built into the language. Here is a small module and a script that uses it.
# geometry.py
import math
def circle_area(radius):
return math.pi * _square(radius)
def _square(x):
return x * x# main.py
from geometry import *
print(circle_area(1)) # 3.141592653589793
try:
_square(2)
except NameError:
print("_square was not imported")
import geometry
print(geometry._square(2)) # 4, still reachable through the moduleA star import skips _square, but geometry._square works fine. The import form decides what you get. The underscore never makes the name unreachable.
Deciding what gets an underscore
Start by asking who is allowed to depend on the name.
Some practical guidelines:
- Everything starts as internal. Adding a public name later is easy. Removing one that users already depend on is a breaking change.
- Helper methods that exist only to support one public method get an underscore.
- Attributes that hold state tied together by an invariant, like
_pricesand_totalabove, get an underscore. Provide public methods that keep them consistent. - Don't add an underscore just to look careful. If callers legitimately need to read and write a value freely, a plain public attribute is correct. A later chapter covers that decision.
Underscores and subclasses
Python has no protected level, but a single underscore is often used for that role. Subclasses are expected to use these names, which makes them an extension point. This is the template method pattern.
class Report:
def render(self):
return "\n".join([self._header(), self._body()])
def _header(self):
return "REPORT"
def _body(self):
raise NotImplementedError("subclasses must provide _body")
class SalesReport(Report):
def _header(self):
return "SALES REPORT"
def _body(self):
return "Total: 1200"
print(SalesReport().render())
# SALES REPORT
# Total: 1200render() is the public method. _header and _body are hooks that subclasses override. Outside callers never call them directly.
This creates a trade-off. Subclasses in other projects may now depend on _header, so renaming it can break them even though it has an underscore. If you intend subclasses to use a name, say so in the docstring. If you don't, subclass authors are on their own when it changes.
Other single-underscore patterns
Don't confuse these with the "internal use" convention:
| Pattern | Meaning |
|---|---|
| `class_`, `type_`, `id_` | A trailing underscore avoids a clash with a keyword or builtin. It is not a privacy signal. |
| `_` as a variable | A throwaway value, as in `for _ in range(3):` or `first, _ = pair`. |
| `__init__`, `__len__` | Double underscores on both sides are special method names ("dunder" methods). Never invent your own. |
| `__balance` | A leading double underscore triggers name mangling, covered in the next chapter. |
Why this matters for properties
The next chapters introduce @property. A property lets you expose a clean public name such as degrees while storing the real value under an internal name such as _degrees. The underscore does the job described here: it marks _degrees as storage that callers shouldn't touch directly.
There is a technical reason for the two names. The public name belongs to the property, so the stored value needs a different name. If both used degrees, the setter's own assignment self.degrees = value would call the setter again, and so on until Python raises RecursionError. The leading underscore is the standard way to choose the second name.
Common mistakes
- Treating the underscore as security. It is not a barrier. Never rely on it to hide secrets or to stop untrusted code from changing state.
- Reaching into another class's
_namesfor convenience. It works today and breaks after an upgrade. If you need the value, ask the author for a public API or wrap the access in one place in your own code. - Underscoring everything. If the whole class interface is underscored, nobody knows how to use it. Keep a small, clear public surface.
- Making a public name internal later without notice. Renaming
totalto_totalis a breaking change for callers. Deprecate it first. - Testing through private names by default. Tests that call
_helperdirectly lock the implementation in place. Prefer testing through the public interface, and make an exception only for complex helpers worth testing alone.
Exercise
A teammate writes cart._prices.append(100) in application code, and cart.total() now returns a stale value. Which side is at fault, and what are two ways to prevent this class of bug?
Show answer
The teammate's code is at fault, because _prices is marked as internal and Cart only promises that add() keeps _total consistent. Two ways to prevent it: (1) add a public method such as Cart.add_many() for the legitimate need, so callers never touch _prices; (2) compute the total from _prices on demand, so there is no second value to fall out of step. Linting with a protected-access check also catches the access before it ships.
Exercise
A module util.py defines def helper(): ..., def _helper(): ..., and no __all__. After from util import *, which of the two functions can you call by bare name, and how could you still call the other one?
Show answer
Only helper() is imported, because star imports skip names starting with an underscore. You can still call _helper by importing it explicitly (from util import _helper) or through the module (import util; util._helper()). To make a star import include _helper, list it in __all__.
Exercise
You are designing a Timer class that stores its start time in an attribute and offers elapsed() to callers. Should the start time be start or _start, and why?
Show answer
Use _start if callers should only learn the time through elapsed(), because the class can then change how it stores time without breaking users. Use start only if you want callers to read and write it freely as part of the public interface.