Sobes.tech
Junior — Middle

What is the difference between one and two underscores in variable or method names?

sobes.tech AI

Answer from AI

In Python, a single underscore at the beginning of a name (e.g., _variable) is a convention indicating that the variable or method is internal (protected) and not intended for use outside the class or module. It does not prevent access but signals to other developers that it is for internal use.

A double underscore at the beginning of a name (e.g., __variable) activates the name mangling mechanism — changing the variable's name to prevent conflicts in subclasses. Python changes the variable's name by adding the class name, making direct access from outside more difficult.

Example:

class MyClass:
    def __init__(self):
        self._protected = 1       # internal use
        self.__private = 2        # name will change to _MyClass__private

obj = MyClass()
print(obj._protected)          # access is possible
# print(obj.__private)         # will raise AttributeError
print(obj._MyClass__private)   # access via name mangling is possible