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

Better Stack Team
Updated on October 5, 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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github