Single and Double Underscores before an Object Name in Python

In Python, underscores serve a completely different purpose than social media usernames. While underscores in usernames help make them unique, in Python, they play a crucial role in variable naming conventions. Python is an interpreted, open-source language, meaning anyone, anywhere, can modify and contribute to your code, just as you can with theirs. 

To maintain clarity and structure, Python follows a set of standards, one of the most important being PEP8 naming conventions. Underscores appear frequently in these conventions, particularly in the naming of methods, functions, and variables. In this blog, we will explore the various ways in which underscores are used in Python.

Table of Contents:

Different Types of Underscores in Python

Underscores in Python are used in different ways to convey specific meaning in code. You will encounter them as a single leading underscore, a single trailing underscore, a single underscore, a single underscore, a double leading underscore, and a double trailing and leading underscore.

Single Leading Underscore (_foo / _variable)

If a class variable or method is named using a single leading underscore, it becomes an “internal” variable or method. This is similar to the notion of having private methods and variables in object-oriented programming languages like Python. Private methods or variables cannot be accessed outside the class

For example, if you have a class named ‘car’ having a private method changing_the_color(). The user will be able to access this method inside the class in other functions and operations, but the moment the control is out of the class, accessing this method will throw an error. Since Python does not have any reserved keywords like private, a single underscore is used. 

Example:

Python

Output:

Explanation: Here, the method and the variable were accessible outside the class, and hence printed an output without throwing an error. 

Boost Your Tech Career with Python – Start Today!
Practical projects, job-ready skills, and expert guidance.
quiz-icon

Single Trailing Underscore (foo_ / variable_)

Whenever you want to use a reserved keyword for naming one of your Python variables or methods, you must use a trailing underscore after it, or the program will throw an exception.

Example:

Error Code

Python

Output:

Single Trailing Underscore - Error Code

Explanation: An error was thrown because we used the reserved keyword class to name the variable. 

Correct Code:

Python

Output:

Single Trailing Underscore - Correct Code

Explanation: Here, using an underscore (_) avoided the error and successfully compiled the code.

Single Underscore (_)

In Python, a single underscore has three major usages. It can act as a placeholder, help ignore unwanted values, or be used by the interpreter to store temporary results.

Ignoring Values in Tuple Unpacking

When unpacking a tuple or list, if you have no use for some of the values and want to ignore them, you can use the underscore as a placeholder. This makes your code cleaner and prevents the creation of unnecessary variables.

Example:

Python

Output: 

Single Underscore - Tuple Unpacking

Explanation: We are unpacking the tuple numbers. We do not want to print the value ‘2’. Therefore, we used an underscore (_) to ignore it and avoided throwing an exception.

Placeholder in Loops

In loops, whenever the loop variable is not needed, an underscore (_) can be used to intentionally indicate to the other developers that the loop variable is not needed and therefore ignored. This avoids naming conflicts and improves code readability.

Example:

Python

Output:

Single Underscore - Place Holder

Explanation: Here, the variable name is replaced with an underscore. The loop runs without any errors and prints “Hello Intellipaat” five times. 

Used by the Python Interpreter (Temporary Result Storage)

When Python is coded or run in a terminal, the interpreter automatically stores the result of the last expression in a special variable called underscore (_). This is useful when you want to quickly use the result of the last operation without having to store it in a separate variable. However, this value is temporary, and it will be overwritten by the next result.

Example:

Python

Output:

Single Underscore - Interpreter

Explanation: As you can see, no variable was assigned to store the result of 3 + 8. The interpreter automatically stores it in the underscore(_).

Double Leading Underscore (__foo/ __variable)

This notifies the interpreter to rewrite the attribute name of subclasses to _class__variable to avoid naming conflicts. This process is known as Name Mangling

This ensures smooth inheritance when you are aware that you might be using the same names in the inherited class as well.

Example:

Python

Output:

Double Leading Underscore

Explanation: Double leading underscores (__) modify variable names to avoid conflicts in inheritance, allowing the child class to access the parent’s “private” variable using its mangled name. 

Double Leading and Trailing Underscores (__foo__)

Adding double leading underscores and double trailing underscores will make your method a dunder method, also called the special or magic method in Python. The dunder method allows a class to define its behaviors for built-in functionalities of Python. For example, we can modify what the add operator, +, does using the __add__ method implementation.

Example:

Python

Output:

Double Leading and Trailing Underscore

Explanation: Here, the __add__ method redefines the “+” operator for vectors according to mathematical rules. As defined, the x part gets added to the x part, and the y part gets added to the y part, outputting (4,6).

Performance of Underscores

Feature Single Underscore Double Underscore
Purpose – Used in place of ‘private’ keyword
– Used as a temporary variable
– Used for name mangling
– Used to declare Dunder Methods
Interpreter Action Not enforced (just a convention) Enforced (name mangling prevents subclass access)
Example _internal_var (internal use) __private_var_ClassName__private_var
Here is the performance consideration of single and double underscores.

Get 100% Hike!

Master Most in Demand Skills Now!

Underscores in Other Programming Languages

Language Use of Underscore
Python – Placeholder to ignore values
– Name mangling
– Dunder methods (e.g., __init__)
Java No special significance (used in variable/function naming)
C++ No special significance (used in variable/function naming)
JavaScript No special significance
Go Blank identifier (_) to ignore values and handle unused variables
C# No special significance
Swift Ignores values in tuple unpacking (e.g., let (x, _) = (1, 2))
Ruby – Unused block parameters (e.g., _)
– Special methods (e.g., __send__)
As you can see, the underscore holds the highest meaning and usage in Python, getting used for name mangling, the Dunder Method, encapsulation, and many more. In programming languages such as Java, C++, JavaScript, and C#, it holds no significance at all.

Common Misconceptions and Pitfalls

  • Even though a single leading underscore (_var) suggests an internal variable, it does not prevent access. Developers can still access and modify these variables, which can lead to unintended consequences. 
  • When importing objects from a file, if from module import *” is used, Python does not import objects whose names start with a single leading underscore, i.e., private methods. 
  • Using a single underscore (_method) does not prevent you from importing them. You can import the private methods by mentioning them specifically. For example, if you have a class ‘intellipaat’ having a private method ‘_write,’ you can import it using ‘from intellipaat import _write’.
  • Excessive use of underscores makes it difficult to read the code and maintain it. Proper documentation is of the essence, especially when you are collaborating with a team or working with complex code.
  • It is advised not to overuse the methods in code. Suppose the result can be achieved by performing some operations on already available objects, methods, and functions. In that case, it is advised that you use them instead of defining a dunder method and making the code complex.

Real-World Examples

Here are some examples to show how underscores are used when making real-world applications.

Case 1: Basic Library Management System

Encapsulation and access specifiers become important when implementing huge systems with many classes and subclasses. Below is an example of the implementation of a library management system. 

Python

Output:

Basic Library Management System Example

Explanation: Here, the eBook class inherits from the Book class. Using double leading underscores indicates to the interpreter to use Name Mangling. Now the _internalcode of the parent class, Book, will be different and inaccessible from the _internalcode of the child class, Ebook.

Case 2: NumPy 2D array

Example:

Python

Output:

Numpy 2D Array Example

Explanation: Here, the underscore (_) is used to ignore the middle row when unpacking the NumPy array. The mean of the entire array is calculated and printed, ignoring any unnecessary values.

Learn Python for Free – Start Coding Today!
Dive into Python with our beginner-friendly course
quiz-icon

Conclusion

You must have gained a better understanding of the meaning of the single and double underscores in an object’s name. Python underscores are more than just basic characters. They are crucial for structuring, organizing, and enhancing the readability and functionality of the code. Underscores are essential for internal variables, conflict avoidance, and object behavior customization. They assist developers in adhering to best practices and conventions that make code easier to maintain.

To take your skills to the next level, check out this Python training course and gain hands-on experience. Also, prepare for job interviews with Python interview questions prepared by industry experts.

Single and Double Underscores before an Object Name in Python – FAQs

Q1. Why does Python use underscores instead of private keywords like other languages?

This is because Python follows the philosophy of “we are all consenting adults” and therefore trusts the developers to follow the conventions rather than enforcing strict rules like other languages.

Q2. What is the meaning of if __ name __ == __ main __?

It checks whether the current script is being run directly as the main script or whether it is getting imported.

Q3. Are there any performance implications to using underscores in Python?

No, there are no performance implications. They are just naming conventions.

Q4. Does using underscores in Python impact performance?

No, underscores are purely a naming convention in Python and do not affect the performance of your code.

Q5. Can the use of underscores improve code maintainability in large-scale projects?

Yes, underscores enhance maintainability by improving clarity and preventing naming conflicts.

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration. 

Full Stack Developer Course Banner