The underscore character (_
) in Python has several important uses and conventions. Understanding these uses can help you write more readable and idiomatic Python code. Below are the primary ways the underscore is used in Python.
1. Single Underscore as a Variable Name
In Python, a single underscore is often used as a temporary or insignificant variable name. This is a convention that signifies that the value of the variable is not important and is used when the value is not needed.
# Example of using underscore as a throwaway variable
for _ in range(5):
print("Hello, world!")
In this example, the underscore is used as a placeholder for the loop variable because the loop variable itself is not used in the loop body.
2. Single Underscore for Unpacking
When unpacking sequences, underscores can be used to ignore certain values. This is useful when you want to unpack only some of the values from a sequence.
# Unpacking a tuple with unused values
x, _, y = (1, 2, 3)
print(x, y) # Output: 1 3
In this example, the value 2
is unpacked but not used, so it is assigned to an underscore.
3. Single Underscore in Interactive Mode
In the Python interactive shell, the underscore holds the result of the last executed expression. This can be useful for quickly referencing previous results.
>> 5 + 3
8
>>> _ * 2
16
Here, the underscore _
refers to the result 8
of the previous operation.
4. Single Underscore in Numeric Literals
Underscores can be used in numeric literals to improve readability. For example, you can use underscores to separate groups of digits in large numbers.
# Numeric literals with underscores for readability
large_number = 1_000_000_000
print(large_number) # Output: 1000000000
This makes the number easier to read, especially when dealing with large values.
5. Double Underscore Prefix and Suffix
In Python, double underscores before and after a name (e.g., __init__
, __str__
) are used for special methods and variables. These are also known as “dunder” methods (short for “double underscore”).
# Example of a special method
class MyClass:
def __init__(self, value):
self.value = value
def __str__(self):
return f"MyClass with value: {self.value}"
obj = MyClass(10)
print(obj) # Output: MyClass with value: 10
Here, __init__
is the constructor method, and __str__
is used to define the string representation of the object.
6. Double Underscore Prefix (Name Mangling)
A name with a double underscore prefix (e.g., __variable
) is subject to name mangling. This means that Python internally changes the name to include the class name, which helps to avoid name conflicts in subclasses.
# Example of name mangling
class MyClass:
def __init__(self):
self.__private = "This is private"
obj = MyClass()
print(obj._MyClass__private) # Output: This is private
In this example, the name __private
is mangled to _MyClass__private
to make it harder to accidentally override in subclasses.
Conclusion
The underscore character in Python serves several purposes, from representing insignificant variables to improving code readability and handling special methods. Understanding these conventions helps in writing cleaner and more Pythonic code. Whether you’re using single or double underscores, knowing their roles will aid you in both reading and writing Python code effectively.