[Python-Dev] Evil setattr hack (original) (raw)
Aahz aahz@pythoncraft.com
Sat, 19 Apr 2003 13:07:00 -0400
- Previous message: [Python-Dev] Evil setattr hack
- Next message: [Python-Dev] Evil setattr hack
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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 "", 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() 'olleh' >>>
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?
class C(object): def _getx(self): print "getting x:", self._x return self._x def _setx(self, value): print "setting x with:", value self._x = value x = property(_getx, _setx)
a = C() a.x = 1 a.x object.setattr(a, 'x', 'foo') a.dict['x'] = 'spam' print a.dict['x']
Aahz (aahz@pythoncraft.com) <*> http://www.pythoncraft.com/
Why is this newsgroup different from all other newsgroups?
- Previous message: [Python-Dev] Evil setattr hack
- Next message: [Python-Dev] Evil setattr hack
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]