Pax0r Pax0r - 1 year ago 122
Python Question

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
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()

Interpreter raised an error:

NameError: name '_TestClass__test' is not defined

So as we can see it tried to name-mangle

I thought that name-mangling should be used only for class variables (when I access them with
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

Answer Source

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download