[Python-Dev] Evil setattr hack
Sat, 19 Apr 2003 13:07:00 -0400
On Sat, Apr 12, 2003, Guido van Rossum wrote:
> Using the dictionary doesn't work either:
> >>> str.__dict__['reverse'] = reverse
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> TypeError: object does not support item assignment
> But here's a trick that *does* work:
> >>> object.__setattr__(str, 'reverse', reverse)
> Proof that it worked:
> >>> "hello".reverse()
This post inspired me to check the way new-style class instances work
with properties. Running the following code will demonstrate that
although the __setattr__ hack is blocked, you can still access the
instance's dict. This can obviously be fixed by using __slots__, but
that seems unwieldy. Should we do anything?
print "getting x:", self._x
def _setx(self, value):
print "setting x with:", value
self._x = value
x = property(_getx, _setx)
a = C()
a.x = 1
object.__setattr__(a, 'x', 'foo')
a.__dict__['x'] = 'spam'
Aahz (firstname.lastname@example.org) <*> http://www.pythoncraft.com/
Why is this newsgroup different from all other newsgroups?