[Python-Dev] Evil setattr hack

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/)