Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Underscore(_) in Python
In Python, the underscore (_) character has several special uses and naming conventions. Understanding these patterns helps you write more Pythonic code and follow established conventions.
Single Underscore in Interpreter
The Python interpreter automatically stores the result of the last expression in the special variable _ ?
# In interactive Python interpreter print(10 + 5) print(_) # Access last result print(_ * 2) # Use it in calculations
15 15 30
Ignoring Values in Unpacking
Use _ as a throwaway variable when you don't need certain values during tuple unpacking ?
# Ignore middle value
x, _, y = (1, 2, 3)
print(f"x = {x}, y = {y}")
# Ignore multiple values
first, *_, last = [1, 2, 3, 4, 5]
print(f"first = {first}, last = {last}")
x = 1, y = 3 first = 1, last = 5
Naming Conventions
Single Leading Underscore
Indicates internal use (weak private) ?
class MyClass:
def __init__(self):
self.public = "Everyone can access"
self._internal = "Internal use hint"
def _helper_method(self):
return "Internal helper"
obj = MyClass()
print(obj.public)
print(obj._internal) # Accessible but not recommended
Everyone can access Internal use hint
Single Trailing Underscore
Avoids conflicts with Python keywords ?
# Avoid keyword conflict
class_ = "MyClass" # 'class' is a keyword
type_ = "string" # 'type' is a built-in
print(f"Class name: {class_}")
print(f"Type: {type_}")
Class name: MyClass Type: string
Double Leading Underscore
Triggers name mangling to avoid attribute conflicts in inheritance ?
class Parent:
def __init__(self):
self.__private = "Parent private"
def show_private(self):
return self.__private
class Child(Parent):
def __init__(self):
super().__init__()
self.__private = "Child private"
child = Child()
print(child.show_private()) # Shows Parent's version
print(child._Child__private) # Mangled name access
Parent private Child private
Magic Methods
Double underscores on both sides define special methods ?
class Calculator:
def __init__(self, value):
self.value = value
def __add__(self, other):
return Calculator(self.value + other.value)
def __str__(self):
return f"Calculator({self.value})"
calc1 = Calculator(10)
calc2 = Calculator(5)
result = calc1 + calc2
print(result)
Calculator(15)
Numeric Separators
Use underscores to improve readability of large numbers ?
# Large numbers with separators
million = 1_000_000
binary = 0b1010_0001
hex_value = 0xFF_EC_DE_5E
print(f"Million: {million}")
print(f"Binary: {binary}")
print(f"Hex: {hex_value}")
Million: 1000000 Binary: 161 Hex: 4293713502
Internationalization Convention
The _ function is commonly used for internationalization (i18n) by convention ?
# Simulated i18n function
def _(text):
translations = {
"Hello": "Hola",
"Goodbye": "Adiós"
}
return translations.get(text, text)
print(_("Hello"))
print(_("Goodbye"))
print(_("Unknown")) # Falls back to original
Hola Adiós Unknown
Summary
| Pattern | Purpose | Example |
|---|---|---|
_ |
Last result, ignore values | x, _, y = (1, 2, 3) |
_var |
Internal use hint | _helper_function() |
var_ |
Avoid keyword conflict | class_ = "MyClass" |
__var |
Name mangling | self.__private |
__var__ |
Magic methods |
__init__, __str__
|
Conclusion
Underscores in Python serve multiple purposes from naming conventions to special interpreter features. Understanding these patterns helps you write cleaner, more maintainable code that follows Python conventions.
