Fundamentals 11 min read

Decoding Python’s Underscore Naming Conventions: From Single to Double Dunders

This article explains the meaning and conventions of single and double leading, trailing, and combined underscores in Python identifiers, demonstrates how name mangling works, and shows practical examples of how these patterns affect variable access, imports, inheritance, and REPL usage.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Decoding Python’s Underscore Naming Conventions: From Single to Double Dunders

1. Single leading underscore _var

A single leading underscore is a convention that signals an identifier is intended for internal use; it does not change program behavior but influences "from module import *" by excluding such names unless __all__ is defined.

class Test:
    def __init__(self):
        self.foo = 11
        self._bar = 23

t = Test()
print(t.foo)   # 11
print(t._bar)  # 23

Because the underscore is only a convention, the attribute remains accessible.

When using wildcard imports, names with a leading underscore are omitted:

# my_module.py

def external_func():
    return 23

def _internal_func():
    return 42

from my_module import *
print(external_func())   # 23
print(_internal_func()) # NameError

2. Single trailing underscore var_

A trailing underscore is used when a desired identifier conflicts with a Python keyword, allowing the name to be used without syntax errors.

def make_object(name, class_):
    pass

3. Double leading underscore __var

Identifiers that start with two underscores trigger name mangling: the interpreter rewrites the name to include the class name, preventing accidental overrides in subclasses.

class Test:
    def __init__(self):
        self.foo = 11
        self._bar = 23
        self.__baz = 42

t = Test()
print(dir(t))
# Output includes '_Test__baz' but not '__baz'

In a subclass, the mangled name is further prefixed with the subclass name:

class ExtendedTest(Test):
    def __init__(self):
        super().__init__()
        self.__baz = 'overridden'

et = ExtendedTest()
print(et._ExtendedTest__baz)  # 'overridden'
print(et._Test__baz)          # 42

Name mangling also applies to methods:

class MangledMethod:
    def __method(self):
        return 42
    def call_it(self):
        return self.__method()

print(MangledMethod().call_it())  # 42

4. Double leading and trailing __var__

Identifiers that both start and end with double underscores are not mangled; they are reserved for special Python methods (e.g., __init__, __call__) and should be avoided for user‑defined names to prevent future conflicts.

5. Single underscore _

A solitary underscore is conventionally used as a throwaway variable in loops or unpacking, indicating the value is irrelevant.

for _ in range(5):
    print('Hello, World.')

color, _, _, mileage = ('red', 'auto', 12, 3812.4)
print(color)   # 'red'
print(mileage) # 3812.4

In the interactive REPL, '_' holds the result of the last evaluated expression, allowing quick reuse without assigning a name.

>> 20 + 3
23
>>> _
23
>>> _.append(1)
>>> _.append(2)
>>> _.append(3)
>>> _
[1, 2, 3]

Python underscore naming patterns – quick reference

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythonnaming conventionsVariablesname manglingunderscoresPEP 8
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.