Open In App

Single Aad Double Underscores in Python

Last Updated : 16 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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, including class attributes and special methods. In this article, we will learn about single and double underscores in Python

What is Single Underscore in Python?

In Python, the single underscore, _, is often used as a temporary or throwaway variable. It serves as a placeholder when the variable itself is not going to be used in the code.

Single Underscore in Python Examples

Below are some of the examples by which we can understand about single underscore in Python:

Temporary Variables

The single underscore is frequently employed as a temporary or throwaway variable. It signifies that the variable is used as a placeholder, and its value may not be utilized in the code.

Python3




for _ in range(5):
    print("Hello")


Output

Hello
Hello
Hello
Hello
Hello


Unused Variable

In this example, a tuple is unpacked, and the underscore signifies that the second value is intentionally ignored in the program logic.

Python3




# Function returning a pair of values
def get_key_value_pair():
    return "key", "value"
 
# Ignoring the first element of the returned pair using a single underscore
_, value = get_key_value_pair()
 
# The first element is ignored, and only the second element is used
print("Value:", value)


Output

Value: value


What is Double Underscore in Python?

Double underscores, __, in Python names are primarily associated with name mangling and special methods, often referred to as “magic” or “dunder” methods.

Double Underscore in Python Examples

Let us understand about double underscore in Python with the help of some examples:

Name Mangling

When double underscores are used as a prefix in a class attribute name, it triggers a mechanism known as name mangling. This process alters the attribute’s name to include the class name, preventing unintentional name clashes in subclasses.

Python3




class MyClass:
    def __init__(self):
        self.__private_variable = 42
 
obj = MyClass()
# Raises AttributeError; the name is now _MyClass__private_variable
print(obj._MyClass__private_variable)
 
print(obj.__private_variable)


Output:

42
ERROR!
Traceback (most recent call last):
File "<string>", line 9, in <module>
AttributeError: 'MyClass' object has no attribute '__private_variable'

“Magic” or Special Methods

Double underscores are integral to defining special methods, often referred to as “magic methods” or “dunder methods.” These methods, such as __init__ and __str__, have double underscores at the beginning and end of their names. They are automatically invoked in specific situations and allow customization of built-in operations.

Python3




class MyClass:
    def __init__(self, value):
        self.value = value
 
    def __str__(self):
        return f"MyClass instance with value {self.value}"
 
obj = MyClass(10)
print(obj)  # Calls __str__ method


Output

MyClass instance with value 10


Special Methods (Dunder Methods)

In this example, a class named `MySpecialClass` defines the `__str__` special method, which returns a custom string representation when the `str()` function is invoked on an instance of the class. An object (`obj`) of the class is created, and its string representation is printed using `str(obj)`.

Python3




class MySpecialClass:
    def __str__(self):
        return "This is a special class"
 
# The __str__ method is a special method invoked by the str() function.
obj = MySpecialClass()
print(str(obj))


Output

This is a special class


Unused Variable (Preventing Name Clashes)

In this example, a loop is iterated five times using the `range(5)` construct, and the double underscore is employed as a convention to indicate that the loop variable is intentionally unused, helping to avoid potential conflicts with existing variable names. The loop body, marked by the comment, performs a generic operation without referencing the loop variable.

Python3




for __ in range(5):
    # Using double underscores to avoid conflicts with existing variable names.
    print("Perform some operation")


Output

Perform some operation
Perform some operation
Perform some operation
Perform some operation
Perform some operation




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads