Single and Double Underscores in Python
Last Updated :
02 Apr, 2025
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.
Python
for _ in range(5):
print("Hello")
OutputHello
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.
Python
# 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)
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.
Python
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.
Python
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
OutputMyClass 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)`.
Python
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))
OutputThis 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.
Python
for __ in range(5):
# Using double underscores to avoid conflicts with existing variable names.
print("Perform some operation")
OutputPerform some operation
Perform some operation
Perform some operation
Perform some operation
Perform some operation
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
Single and Double Quotes | Python
Python string functions are very popular. There are two ways to represent strings in python. String is enclosed either with single quotes or double quotes. Both the ways (single or double quotes) are correct depending upon the requirement. Sometimes we have to use quotes (single or double quotes) to
3 min read
Underscore (_) in Python
In this article, we are going to see Underscore (_) in Python. Following are different places where "_" is used in Python: Single Underscore:Single Underscore in InterpreterSingle Underscore after a nameSingle Underscore before a nameSingle underscore in numeric literalsDouble Underscore:Double unde
3 min read
Print Single and Multiple variable in Python
In Python, printing single and multiple variables refers to displaying the values stored in one or more variables using the print() function. Let's look at ways how we can print variables in Python: Printing a Single Variable in PythonThe simplest form of output is displaying the value of a single v
2 min read
Underscore _.get() Function
Underscore.js is a JavaScript library that provides a lot of useful functions that help in the programming in a big way like the map, filter, invokes, etc even without using any built-in objects. The _.get() function is an inbuilt function in the Underscore.js library of JavaScript which is used to
2 min read
Python string | ascii_uppercase
In Python3, ascii_uppercase is a pre-initialized string used as a string constant. In Python, the string ascii_uppercase will give the uppercase letters âABCDEFGHIJKLMNOPQRSTUVWXYZâ. Syntax : string.ascii_uppercase Parameters: Doesn't take any parameter, since it's not a function. Returns: Return al
2 min read
Scope Resolution in Python | LEGB Rule
Here, we will discuss different concepts such as namespace, scope, and LEGB rule in Python. What are Namespaces in Python A python namespace is a container where names are mapped to objects, they are used to avoid confusion in cases where the same names exist in different namespaces. They are create
5 min read
__file__ (A Special variable) in Python
A double underscore variable in Python is usually referred to as a dunder. A dunder variable is a variable that Python has defined so that it can use it in a "Special way". This Special way depends on the variable that is being used. Note: For more information, refer to Dunder or magic methods in P
2 min read
Python Lambda with underscore as an argument
In Python, we use the lambda keyword to declare an anonymous function. Lambda function behaves in the same way as regular functions behave that are declared using the 'def' keyword. The following are some of the characteristics of Python lambda functions: A lambda function can take more than one num
1 min read
What are All the Uses of an Underscore in Scala?
The underscore (_) is a symbol frequently employed in Scala, serving as a handy tool to simplify and condense code. While it's dubbed "syntactic sugar" for its ability to streamline code, its extensive use can sometimes lead to confusion and make the learning process more challenging. This article f
9 min read