The underscore (_) in Python is more than just a minor character—it holds significant roles in writing clear and efficient code. While Python is known for its readability, the clever use of underscore can make code sections more concise and intention-revealing.
Ignoring Values During Unpacking
Sometimes, you might only need some elements from an iterable. The underscore is commonly used as a placeholder to indicate deliberate ignoring of values during unpacking.
point = (5, 9)
x, _ = point
print(x)
This will print the x
coordinate, demonstrating how the y
coordinate is ignored.
5
In the example above, only the x
coordinate is important, so the y
coordinate is ignored using _
.
When dealing with iterables that contain more elements, the use of underscores can help clarify which elements are purposely ignored. Here’s how you might unpack a list with more items:
data = ['apple', 'banana', 'cherry', 'date']
first_fruit, _, _, last_fruit = data
print(first_fruit)
print(last_fruit)
This shows the first and last fruits in the list, ignoring the middle items.
apple
date
In this list, only the first_fruit
and last_fruit
items are extracted and assigned variable names, while the middle items are disregarded, showcasing how underscores can ignore multiple values seamlessly.
Use as a Loop Placeholder
When you need to perform an action multiple times but do not need the loop variable, underscore acts as a placeholder.
for _ in range(3):
print("Hello!")
This demonstrates repeating an action three times using a loop variable placeholder.
Hello!
Hello!
Hello!
Here, underscore signifies that the loop variable is irrelevant.
Accessing the Last Result in the Python REPL
In the interactive Python shell (REPL), _
holds the value of the last executed expression, allowing for quick access to results.
>>> 5 + 3
8
>>> _ * 2
16
This illustrates quick calculations in the REPL where _
accesses the last result.
Formatting Large Numbers
To enhance the readability of large numbers, Python supports the use of underscores as visual separators.
large_number = 1_000_000
print(large_number)
This highlights how underscores separate digits to improve readability.
1000000
This approach improves clarity without altering the number's value.
Another use case involves storing a precise float value where underscores help highlight the logical parts of the number:
precise_value = 3.141_592_653_589
print(precise_value)
Shows how underscores make the mathematical constant Pi more readable.
3.141592653589
In this example, underscores are used to separate groups of digits, making the mathematical constant Pi more readable without affecting its accuracy.
Defining "Private" Methods and Variables in Classes
While Python does not enforce access control like some other languages, using underscores helps signal that certain methods or variables are intended for internal use only.
Single Underscore Prefix
Methods or variables with a single underscore prefix are treated as "protected" by convention.
class MyClass:
def _internal_method(self):
print("This is intended for internal use.")
def public_method(self):
print("This is a public method.")
self._internal_method()
obj = MyClass()
obj._internal_method() # This will work, but it's not recommended as the underscore suggests it's for internal use.
obj.public_method() # This is the recommended way to access the internal method.
Although accessible externally, it's a gentle reminder they are meant for internal use only.
Double Underscore Prefix
For stronger name mangling protection, a double underscore prefix causes the Python interpreter to rewrite the name to avoid clashes.
class MyClass:
def __hidden_method(self):
print("This method is hidden by name mangling.")
obj = MyClass()
obj.__hidden_method() # This will raise an AttributeError)
This means accessing __hidden_method
directly from outside the class is disallowed, promoting encapsulation.
Conclusion
The underscore (_
) in Python stands out as a multifaceted tool that enhances code readability, organization, and intention. Whether ignoring values during unpacking, acting as a loop placeholder, accessing the last result in REPL, formatting large numbers, or denoting "private" definitions in classes, the underscore brings clarity and professionalism to Python code. By integrating these conventions into your coding practice, you can write cleaner, more Pythonic programs.