Home
Understanding Double Underscores and the Pythonic Way to Use Them
In Python, the repetition of the underscore character is more than just a stylistic choice; it is a fundamental part of the language's syntax and philosophy. When developers search for "underscore underscore," they are usually encountering the term Dunder, which is a portmanteau of "Double Under." This refers to identifiers that start and end with two underscores, such as __init__ or __str__.
Depending on where these underscores are placed—whether at the beginning, the end, or both—the Python interpreter changes how it treats a variable or method. Understanding these nuances is essential for writing clean, efficient, and "Pythonic" code.
Quick Answer to the Double Underscore Mystery
In Python, a double underscore prefix and suffix (e.g., __name__) signifies a Special Method or Magic Method, often called a Dunder method. These are reserved by the language to perform specific tasks, like initializing an object or overloading operators.
A double underscore prefix alone (e.g., __private_variable) triggers Name Mangling, a mechanism the Python interpreter uses to prevent naming conflicts in class inheritance.
| Syntax | Common Name | Primary Purpose |
|---|---|---|
_variable |
Single Leading Underscore | Conventional "internal use" hint; not enforced by the runtime. |
variable_ |
Single Trailing Underscore | Used to avoid conflicts with Python keywords (e.g., class_). |
__variable |
Double Leading Underscore | Triggers name mangling to avoid subclass naming collisions. |
__variable__ |
Dunder Method | Reserved special methods used for language-level features. |
_ |
Single Underscore | Temporary/throwaway variable or the last result in a REPL. |
The Role of the Single Underscore in Python
Before diving into the complex world of double underscores, it is important to understand the base case: the single underscore. It serves multiple purposes depending on the context.
Using the Underscore as a Throwaway Variable
One of the most common sights in professional Python codebases is the single underscore used in loops or unpacking. It signals to other developers (and static analysis tools like linters) that the value being assigned is intentionally ignored.
In my experience refactoring data processing pipelines, this is invaluable for readability. Consider a function that returns a 3-tuple representing coordinates (x, y, z), but you only need the elevation (z):
-
Topic: What Is The Role of Underscore (_) in Python?https://www.analyticsvidhya.com/back-channel/download-pdf.php?pid=140254&next=
-
Topic: Underscore (_) in Python - GeeksforGeekshttps://www.geeksforgeeks.org/underscore-_-python/amp/
-
Topic: How does underscore \"_\" work in Python files?https://www.tutorialspoint.com/article/how-does-underscore-quot-quot-work-in-python-files