What is the meaning of single and double underscore before an object name in Python?

Better Stack Team
Updated on February 3, 2023

In Python, single underscore _ before an object name means that the object is meant to be private, and shouldn't be directly accessed from outside the class. However, it is just a naming convention, and there is nothing actually stopping you from accessing these objects.

On the other hand, double underscore __ before an object name is used to create so-called "name mangling". This is a way to make instance variables less likely to collide with variables in subclasses. When a class attribute name is preceded by two underscores, Python replaces each underscore and the character following it with the name of the class, in order to avoid name clashes between attributes in different classes. For example:

 
class MyClass:
    def __init__(self):
        self.__private = 42

obj = MyClass()
print(obj.__private)  # this will raise an AttributeError
print(obj._MyClass__private)  # this works

Name mangling is not intended to provide real privacy; it is just a way to avoid accidental name clashes between class attributes. If you really want to prevent external access to an object, you should use the private module, which provides a more robust way of creating private variables in Python.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →