Python, as a flexible and intuitive language, introduces many constructs that enable the ease of coding. One such construct is the underscore ( _
), a special character with multiple uses, ranging from variable naming to interpreter purposes, and more. For novice programmers, underscores might appear confusing, but understanding their purpose can significantly enhance your Python programming prowess. This article delves into an in-depth exploration of Python underscores, demystifying their diverse usages and significance.
Single Underscore
- As a Throwaway Variable
Often in Python, we come across a situation where we need to iterate over a range or any iterable, but we don’t intend to use the variable inside the loop. In such scenarios, the single underscore is employed as a ‘throwaway’ variable, indicating that the loop variable is being intentionally ignored.
Advertisement12for _ in range(5):print("Hello, Python!") - After a Name
In Python, a single underscore after a name is used as a naming convention to indicate a name is meant for internal use. It suggests that a variable, method, or attribute is intended for internal use within the class, module, or function, and it’s not part of the API.
1234class MyClass:def __init__(self):self.public_var = "I'm public!"self._internal_var = "I'm internal!"Although Python doesn’t enforce privacy with these names, the underscore is a strong hint to the programmer that it’s intended for internal use.
Double Underscore (Dunder)
- Before a Name
When you see a name prefixed with double underscores (
__
), it’s Python’s way of name mangling. This is primarily to avoid naming conflicts with names in subclasses. Python automatically prefixes the name with a class name.123class MyClass:def __init__(self):self.__private_var = "I'm very private!"Here, `
__private_var
` would be mangled to `_MyClass__private_var
`, thereby avoiding any potential naming conflicts. - Surrounding a Name (Magic Methods)
Double underscores both before and after a name have a special meaning. These are associated with Python’s magic methods. These are special methods that you can define to add “magic” to your classes, like overloading operators or implementing protocol methods. Magic methods are an essential part of Python’s object-oriented features.
123456class MagicClass:def __init__(self, num):self.num = numdef __str__(self):return f"A MagicClass instance with number {self.num}"In the above code, `
__str__
` is a magic method that defines how the class should be converted to a string.
Single Underscore in Interpreter
In the Python interpreter, a single underscore has another interesting usage. It is used to hold the result of the last executed expression.
1 2 3 4 | >>> 5 + 5 10 >>> _ 10 |
The _
gives the result of the last executed statement, i.e., 10 in this case.
Double Underscore in Numeric Literals
Python (from version 3.6 onward) also allows underscores in numeric literals. This is purely for enhancing readability for humans. For example, you could write one million as 1_000_000, and Python would interpret it as 1000000.
1 2 3 | >>> num = 1_000_000 >>> num 1000000 |
The underscore in numeric literals doesn’t affect the value; it’s just a readability feature.
Conclusion
Underscores in Python are far from an insignificant detail. They have well-defined purposes, depending on their placement and quantity. Understanding the usage of underscores can not only help make your code cleaner and more idiomatic but also lead you toward harnessing Python’s full potential. Happy Pythoning!