Python private attribute annoyance

Having some Java history I do like the concept of protected and private attributes for hiding the implementation details. I also like the forgiving way of Python when accessing those attributes as it doesn’t do any access checking and does allow access to private attributes e.g. for debugging purposes:

This attribute here

class A(object):     def __init__(self):         self.__a = 1

can be accessed like this

a = A() print a._A__a

The concept of prepending the classes name to the attribute’s name is called “name mangling”. This is an easy solution for hiding the private value from the interface.

However I just tripped over a small issue with name mangling here. Consider the following example which is a common pattern when calculating resource-
hungry values:

class A(object):     def a(self):         if not hasattr(self, '__a'):             print "generating a"             self.__a = 1         return self.__a

Now let’s run the method:

>>> a = A() >>> a.a() generating a 1 >>> a.a() generating a 1

Obviously hasattr doesn’t check for private attributes as expected and the value gets recalulated over and over again. What I should actually do is check for ‘_A__a’ which is kind of counterintuitive here. See also

Now that was annoying.