Pages

2011-04-27

Python's "private name mangling" uncoolness

This:

def __h0la():
print("H0la")

class Foo:
def blah(self):
__h0la()

f = Foo()
f.blah()


throws:

joe@lark:~/sandbox/python$ python pvt.py 
Traceback (most recent call last):
File "pvt.py", line 10, in
f.blah()
File "pvt.py", line 7, in blah
__h0la()
NameError: global name '_Foo__h0la' is not defined


And this explains the behaviour:
Private name mangling: When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class. Private names are..


The word "TEXTUALLY", is important here. Basically if there is an "__X" occurring within a class definition, immaterial of it referring to something else out side the class, it is 'name mangled'.

I dont know about you, but my stomach does not feel THAT good. :-/

2 comments:

Balachandran S said...

Looks bad. It shouldn't mangle those that are not part of the class. I never knew this happens in python :(

Joe Steeve said...

Sigh! :-/