Search code examples
pythoncpythonname-mangling

Python name mangling on global variable with __


When I created a module-level variable with __ and tried to access it inside a method of a class (using global keyword) the name-mangling occured.

Let me show an example:

__test = 'asd'  # module level variable with __


class TestClass(object):
    def test(self):
        global __test
        print(__test)  # trying to access this variable


a = TestClass()
a.test()

Interpreter raised an error:

NameError: name '_TestClass__test' is not defined

So as we can see it tried to name-mangle __test into _TestClass__test.

I thought that name-mangling should be used only for class variables (when I access them with self or class name).

Is it a well-defined behaviour that I have not be aware of or it is some kind of Python bug?

I tested it on CPython 3.5


Solution

  • Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.

    (from the Python documentation, emphasis mine)