How to use Single Underscore _ in Python Variable
In this article, we will learn how to use the single underscore '_' character in Python variables. We will discuss various properties of single underscore and some custom codes as well.
(_) in Python is treated as a throwaway variable. We can use the single underscore with Python variables. Let us discuss three ways with different examples to understand the working of the single underscore.
1. Single Leading Underscore
A single underscore can be used before a Python variable name. It is like a convention that is used to specify that the variable name is considered now a private variable. It should be considered an implementation detail and subject to change without notice. It gives an idea to programmers that the variables with a single underscore are intended for internal use only.
The below example puts a single underscore before the bar variable making it private. When we instantiate the object of this class and tries to access the _bar variable, this convention still allows accessing the _bar variable. That is why it is called a "weak private indicator".
class Test: def __init__(self): self.foo = 11 self._bar = 23 obj = Test() print(obj.foo) print(obj._bar)
2. Single Trailing Underscore
A single underscore can also be used after a Python variable name. By using a single underscore after a keyword, that keyword can be used as a variable. We might need to use keywords like
max as variables but cannot use them. This convention allows Python to do so. It avoids naming conflict with Python keywords.
The below example shows two different things. Firstly, we use the class as a variable name but got an error. Secondly, when we use a single underscore after class and then pass it as a variable, the program works fine.
#class is a keyword >>> def func1(name, class): SyntaxError: "invalid syntax" #class is a variable >>> def func2(name, class_): ... pass
3. Single Underscore for ignoring values
Single underscore is also used in place of variables whose value is not going to be used further like in loops or for ignoring values. It happens often that we do not want to return values, so at that time assign those values to a single underscore. It used as a throwaway variable here.
Example: Ignore a value when unpacking
a,b,_,_ = my_method(var1)
Example: Ignore the index of for loop
a = 9 for _ in range(4): a = a-2 print(a, end=" ")
7 5 3 1
In this article, we learned to use the single underscore in three different ways. We discussed why it is called a weak indicator in Python. We saw different examples of each.