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