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


In Python, a single underscore (_) before an object name is used as a hint to indicate that the object is intended to be private and not part of the public API. This is a convention only and does not enforce any restrictions on accessing the object. A double underscore (__) before an object name triggers name mangling, which makes the object effectively private. Name mangling adds the name of the class to the front of the object name, making it difficult to access from outside the class. Here's an example:

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

    def get_private_attribute(self):
        return self.__private_attribute

my_obj = MyClass()
print(my_obj.__private_attribute) # Raises an AttributeError
print(my_obj._MyClass__private_attribute) # 42
In this example, the __private_attribute is declared with double underscores and is effectively private. Attempting to access the object directly from outside the class raises an AttributeError. To access the object, you need to use the mangled name, which is the name of the class concatenated to the front of the object name with a single underscore (e.g., _MyClass__private_attribute).

It's important to note that name mangling is intended to be a last resort for making objects private and should not be relied upon as the primary means of encapsulation. The convention of using a single underscore for objects that are intended to be private is a better approach for making objects private in a way that is more transparent to the users of the class.
Recommended Course

Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.