In Python, underscores have different meanings depending on how they are used. The single underscore (_) and double underscore (__) each serve specific purposes. They are commonly used in different situations, such as for variable names, method names, and more.
Single Underscore
Single underscore (_) in Python is used in various ways to improve code readability and organization. It can serve as a placeholder in loops, ignore specific values when unpacking, store the result of the last evaluated expression in the interactive shell, and indicate that a variable is intended for internal use within a class or module.
Example 1: Single Underscore In Interpreter
This code demonstrates the use of a single underscore (_
) in the Python interactive shell:
Single Underscore In InterpreterExplanation:
- Initially, the underscore (_) was used by itself, which resulted in a NameError because _ hasn't been assigned any value at that point.
- After performing the operation a + b, the result 20 is stored in _ (since Python automatically assigns the result of the last operation to _ in the interactive shell).
- The value of _ is then used in further calculations (_ * 2 and _ / 2).
Example 2: Single Underscore for ignoring values
This example demonstrates how the single underscore (_) is used to ignore values in Python, which is particularly useful when you don't need to use certain values in a loop or when unpacking a tuple/list.
Python
# Ignore a value of specific location/index
for _ in range(10):
print ("Test")
# Ignore a value when unpacking
a,b,_,_ = my_method(var1)
Explanation:
- The loop iterates 10 times, but the loop variable is ignored by using _. The underscore indicates that we don't need to use the loop variable itself, we just want the loop to run 10 times and print "Test" on each iteration.
- my_method(var1) returns a tuple or list with multiple values. The underscore (_) is used to ignore specific values in the returned sequence. In this case, the third and fourth values are being ignored, and only a and b are assigned values.
Example 3: Single Underscore after a nameÂ
Python has its own default keywords which we can not use as the variable name. To avoid such conflict between python keyword and variable we use underscore after the nameÂ
Python
class MyClass():
def __init__(self):
print("OWK")
def my_definition(var1=1, class_=MyClass):
print(var1)
print(class_)
my_definition()
Output1
<class '__main__.MyClass'>
Explanation:
- The name class_ is used instead of class because class is a reserved keyword in Python, meaning it cannot be used as a variable or function name. By adding an underscore (class_), you avoid the conflict while still conveying that it represents a class.
- The function my_definition() has two parameters: var1 (with a default value of 1) and class_ (with a default value of MyClass).
- The function prints both the value of var1 and class_.
Example 4: Single Underscore before a name
This example demonstrates the use of a single underscore (_) before a variable or method name to indicate that it is intended to be private or for internal use only, though Python does not enforce strict privacy rules. It is just a convention to signal that a variable should not be accessed directly outside the class.
Python
class Prefix:
def __init__(self):
self.public = 10
self._private = 12
test = Prefix()
print(test.public)
print(test._private)
Explanation:
- self.public = 10 is a regular public attribute. It can be accessed directly from outside the class.
- self._private = 12 is intended to be a "private" attribute. The single underscore before the name _private is a convention to indicate that this variable should not be accessed directly from outside the class.
- test.public is accessed directly, and Python allows this because it is a public attribute.
- test._private is also accessible, even though the underscore suggests it should not be accessed directly.
Example 5: Single underscore in numeric literals
The Python syntax is utilized such that underscores can be used as visual separators for digit grouping reasons to boost readability. This is a typical feature of most current languages and can aid in the readability of long literals, or literals whose value should clearly separated into portions.
Python
# grouping decimal for easy readability of long literals
amount = 10_000_000.0
# grouping hexadecimal for easy readability of long literals
addr = 0xCAFE_F00D
# grouping bits for easy readability of long literals
flags = 0b_0011_1111_0100_1110
Double underscore
In Python, a double underscore (__) before a variable or method name has a special significance. It is commonly used for name mangling, a technique that helps avoid conflicts in subclass inheritance.
Example 1: Double Underscore before a name
The leading double underscore tells the Python interpreter to rewrite the name in order to avoid conflict in a subclass. Interpreter changes variable name with class extension and that feature known as the Mangling.Â
Python
class Myclass():
def __init__(self):
self.__variable = 10
Calling from Interpreter
testFile.py The Python interpreter modifies the variable name with ___. So Multiple times It uses as a Private member because another class can not access that variable directly. The main purpose for __ is to use variable /method in class only If you want to use it outside of the class you can make it public.
Python
class Myclass():
def __init__(self):
self.__variable = 10
def func(self)
print(self.__variable)
Calling from Interpreter
Example 2: Double underscore before and after a name
The name starts with __ and ends with the same considering special methods in Python. Python provides these methods to use as the operator overloading depending on the user. Python provides this convention to differentiate between the user-defined function with the module's functionÂ
Python
class Myclass():
def __add__(self,a,b):
print (a*b)
Calling from Interpreter
Similar Reads
Role of Underscores '_' in Python
The Underscore (_) is an eccentric character in Python. It can be used in many ways in a Python program. The various uses of underscore (_) in Python are: 1) Use in Interpreter: Python immediately saves the value of the last expression in the interpreter in this unique variable. Underscore (_) can a
3 min read
Triple Quotes in Python
In Python, triple quotes let us write strings that span multiple lines, using either three single quotes (''') or three double quotes ("""). While theyâre most often used in docstrings (the text that explains how code works), they also have other features that can be used in a variety of situations
2 min read
Single and Double Underscores in Python
In Python, naming conventions play a crucial role in code readability and maintainability. Single and double underscores, when used in names, convey specific meanings and conventions. These naming conventions are widely adopted in the Python community and are often utilized in various contexts, incl
3 min read
str() vs repr() in Python
In Python, the str() and repr() functions are used to obtain string representations of objects. While they may seem similar at first glance, there are some differences in how they behave. Both of the functions can be helpful in debugging or printing useful information about the object. Python str()
3 min read
re.search() in Python
re.search() method in Python helps to find patterns in strings. It scans through the entire string and returns the first match it finds. This method is part of Python's re-module, which allows us to work with regular expressions (regex) simply. Example:Pythonimport re s = "Hello, welcome to the worl
3 min read
__rmul__ in Python
For every operator sign, there is an underlying mechanism. This underlying mechanism is a special method that will be called during the operator action. This special method is called magical method. For every arithmetic calculation like +, -, *, /, we require 2 operands to carry out operator functio
4 min read
re.subn() in Python
re.subn() method in Python is used to search for a pattern in a string and replace it with a new substring. It not only performs the replacement but also tells us how many times the replacement was made. We can use this method when we need to replace patterns or regular expressions in text and get a
3 min read
reflection in Python
Reflection refers to the ability for code to be able to examine attributes about objects that might be passed as parameters to a function. For example, if we write type(obj) then Python will return an object which represents the type of obj. Using reflection, we can write one recursive reverse funct
3 min read
Working with Unicode in Python
Unicode serves as the global standard for character encoding, ensuring uniform text representation across diverse computing environments. Python, a widely used programming language, adopts the Unicode Standard for its strings, facilitating internationalization in software development. This tutorial
3 min read
string.whitespace in Python
In Python, string.whitespace is a string containing all the characters that are considered whitespace. Whitespace characters include spaces, tabs, newlines and other characters that create space in text. string.whitespace constant is part of the string module, which provides a collection of string o
3 min read