[Python-Dev] Evil setattr hack (original) (raw)

Guido van Rossum guido@python.org
Sat, 19 Apr 2003 13:22:57 -0400


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']

I see nothing wrong with that. It falls in the category "don't do that", but I don't see why we should try to make it impossible.

The thing with attributes of built-in types was different. This can affect multiple interpreters, which is evil. It also is too attractive to expect people not to use it if it works (since many people think they have a need to modify built-in types). That's why I go to extra lengths to make it impossible, not just hard.

--Guido van Rossum (home page: http://www.python.org/~guido/)