Understanding the Underscore (_) in Python: Uses and Conventions
This article explains the versatile uses of the underscore (_) in Python, covering temporary variables in REPL, loop placeholders, tuple unpacking, translation functions, numeric literals, naming‑conflict avoidance, protected and private attributes, and special magic methods, with clear code examples for each case.
The underscore (_) in Python serves many purposes beyond a simple character, acting as a convention for temporary variables, placeholders, ignored values, translation functions, readable numeric literals, and mechanisms to avoid naming conflicts.
Temporary variable in REPL:
> 1 + 1
2
>> _
2
>> a = 2 + 2
>> _
2In an interactive REPL session, _ stores the result of the last expression that is not None , similar to a calculator's ANS key.
Loop placeholder:
nums = 13
for _ in range(nums):
fun_oper()Here _ indicates that the loop variable is intentionally ignored.
Tuple unpacking:
city, _, code = ('Beijing', 21536000, '010')
print(city, code) # 输出 Beijing 010The underscore discards the middle element that is not needed.
Internationalization function:
import gettext
zh = gettext.translation('dict', 'locale', languages=['zh_CN'])
zh.install()
_('hello world') # 根据字典文件返回相应的翻译文本By convention, _ is used as an alias for the gettext translation function.
Readable numeric literals:
a = 9_999_999_999
print(a) # 输出 9999999999Underscores improve the readability of large numbers without affecting their value.
Avoiding naming conflicts:
def tag(name, *content, class_):
passAppending an underscore to a name (e.g., class_ ) prevents clashes with Python reserved keywords.
Protected variables (single leading underscore):
class Tools:
_moto_type = 'L15b2'
_wheel_type = 'michelin'
def drive(self):
self._start_engine()
self._drive_wheel()
def _start_engine(self):
print(f'start engine {_moto_type}')
def _drive_wheel(self):
print(f'drive wheel {_wheel_type}')Names starting with a single underscore signal that they are intended for internal use only.
Private variables (double leading underscore):
class Car:
def __init__(self):
self.brand = 'Honda'
self._moto_type = 'L15B2'
self.__wheel_type = 'michelin'
def drive(self):
print(f'Start the engine {self._moto_type}, drive the wheel {self.__wheel_type}, I get a running {self.brand} car')Double underscores trigger name mangling, making the attribute harder to access from outside the class.
Magic methods (double underscores before and after):
class Car:
...
def __repr__(self):
return f'***Car {self.brand}: with {self._moto_type} Engine, {self.__wheel_type} Wheel***'Special methods like __repr__ define how objects are represented as strings, enabling more informative debugging output.
Overall, understanding these underscore conventions helps write clearer, more maintainable Python code.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.