Sub topic 3
Single underscore: signaling internal use
This chapter assumes you can define classes with __init__, assign instance attributes, and catch exceptions. You do not need to know properties yet.
Python has no private attributes
Python does not enforce access control. Any code can read or change any attribute of an object. Instead of locks, Python uses a naming convention: a name that starts with one underscore means "internal, not part of the public interface."
class Counter:
def __init__(self):
self._count = 0
def increment(self):
self._count += 1
def current(self):
return self._count
c = Counter()
c.increment()
print(c.current()) # 1
print(c._count) # 1, it works, but you were warned
c._count = 99 # also works
print(c.current()) # 99The underscore does not stop c._count = 99. It tells readers that _count is an implementation detail. The class author may rename it, remove it, or change its type in a later version without warning.
What the convention tells people
The underscore is a contract between the class author and the class user.
- Names without an underscore are public. You promise to keep them stable.
- Names with one leading underscore are internal. You reserve the right to change them.
- Users who touch internal names accept the risk when the class changes.
This applies to methods and module-level names as well as attributes. A method called _validate is a helper for the class itself. A function called _parse_line in a module is not meant to be imported by other code.
The one place Python does act on it
The underscore has one small effect in the language. from module import * skips names that start with an underscore (unless the module lists them in __all__). Normal imports such as import module and from module import _name still work.
# helpers.py
def public_tool():
return "public"
def _internal_tool():
return "internal"# main.py
from helpers import *
print(public_tool()) # public
try:
_internal_tool()
except NameError:
print("not imported by *")
import helpers
print(helpers._internal_tool()) # internalWhy this matters for properties
Suppose you publish a class with a plain temperature attribute. Later you need to check values before storing them. If users read obj.temperature directly, you cannot add checks without changing how they use it.
A common pattern is to store the real value in _temperature and expose a public name through a property. The underscore marks the storage as internal, and the public name stays stable. The next chapters build that pattern. For now, the habit to adopt is simple: decide which names are your interface, and prefix everything else with _.
Common mistakes
- Treating
_nameas truly private and storing secrets in it. Anyone can read it. - Accessing another object's
_namein your own code because it is convenient. This breaks when the class changes. - Prefixing every attribute with an underscore "just in case." If users legitimately need a value, make it public.
- Confusing
_namewith__name. The double underscore triggers name mangling, which the next chapter covers.
Exercise
A library class has an attribute _cache. Your code reads obj._cache to speed something up. The library's next release replaces _cache with _store. Whose responsibility is the breakage, and what does Python do when your code runs?
Show answer
The breakage is yours, because the underscore marked _cache as internal and the author never promised to keep it. Python raises AttributeError when your code reads obj._cache, since it does not treat underscore names specially at access time. The fix is to use the library's public interface, or ask the author to add one.
Exercise
Given a module that defines report() and _format_row(), which names does from module import * bring in, and can you still call module._format_row() after import module?
Show answer
Only report is imported by * (assuming no __all__). Yes, module._format_row() still works after import module, because the underscore is only a convention and import * is the one place Python skips such names.