liveBook · Manning

Leading underscore convention

As explained in Python How-To

The leading underscore convention prefixes an identifier with an underscore to signal intended internal or non-public use without enforcing access restrictions.

Prefix a method or attribute with one underscore to signal that it is intended for internal, non-public use. Python does not enforce this boundary: outside code can still access the member. section 8.3.1

Hide an implementation method from normal suggestions

class Note: def _format_note(self): return "formatted note" def save(self): return self._format_note() Name the helper _format_note when callers should use save instead. IDE autocomplete can omit the underscored method for outside users while retaining it within the class. section 8.3.1

Use the convention to make intent clear and keep interfaces easier to navigate:

  • Prefix methods that users do not need to call directly, such as _format_note. section 8.3.1
  • Apply the same convention to attributes when they are intended for internal use. section 8.3.1
  • Do not confuse the convention with access control: the underscored member remains available if someone explicitly refers to it. section 8.3.1
  • Distinguish this use from underscores in unpacking, where _ marks an unwanted item rather than a nonpublic class member. section 4.4.3
Figure 8.4 Different autocompletion hints provided for the instance object. It’s less desirable if the autocompletion hints include functions that users don’t need to use—in this case, the format_note method.
CH08_F04_Cui

Compare autocomplete suggestions that include a public format_note method with suggestions that omit its underscored form. section 8.3.1

How Python How-To covers it

How deep it goes
Defines the naming convention and its autocomplete effects, while stopping short of enforcing access restrictions.
Examples
Uses _format_note, protected class members, and a challenge to rename applicable methods as nonpublic.
What it assumes
Assumes familiarity with Python classes and members while treating access-control conventions without requiring private or protected keywords.
What you can do after
Apply it via Python naming conventions to communicate which methods and attributes users should avoid calling directly.
How it connects
Connects encapsulation with Python classes, methods, attributes, and IDE autocomplete.

Also explained in

Compare how 2 books explain leading underscore convention →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.