Why less emphasis on private data?

Duncan Booth duncan.booth at invalid.invalid
Mon Jan 8 11:37:48 CET 2007

"Paul Boddie" <paul at boddie.org.uk> wrote:

> Paul Rubin wrote:
>> Right, the problem is if those methods start changing the "private"
>> variable.  I should have been more explicit about that.
>> class A:
>>    def __init__(self):
>>       self.__x = 3
>>    def foo(self):
>>       return self.__x
>> class B(A): pass
>> class A(B):
>>    def bar(self):
>>      self.__x = 5   # clobbers private variable of earlier class named A
> Has this ever been reported as a bug in Python? I could imagine more
> sophisticated "name mangling": something to do with the identity of the
> class might be sufficient, although that would make the tolerated
> "subversive" access to private attributes rather difficult.
> Paul
If it worries you then you can always check for it and disallow any 
hierarchies where it could be a problem. For that matter PyChecker ought to 
be able to catch this situation (maybe it already does, I haven't looked).

>>> class SafetyNet(type):
	def __new__(cls, name, bases, dct):
		print "new",name
		c = type.__new__(cls, name, bases, dct)
		assert not name in [b.__name__ for b in c.__mro__[1:]]
		return c

>>> __metaclass__ = SafetyNet
>>> class A: pass

new A
>>> class B(A): pass

new B
>>> class A(B): pass

new A

Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    class A(B): pass
  File "<pyshell#17>", line 5, in __new__
    assert not name in [b.__name__ for b in c.__mro__[1:]]

More information about the Python-list mailing list