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

Guido van Rossum guido@python.org
Sat, 12 Apr 2003 09:43:52 -0400


Someone accidentally discovered a way to set attributes of built-in types, even though the implementation tries to prevent this. For example, you cannot modify the str type to add a new method. Let's define the method first:

>>> def reverse(self):
...     return self[::-1]
...
>>>

Using direct attribute assignment doesn't work:

>>> str.reverse = reverse
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: can't set attributes of built-in/extension type 'str'
>>>

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()
'olleh'
>>> 

What to do about this? I really don't want changes to built-in types to become a standard "hack", because there are all sorts of things that could go wrong. (For one, built-in type objects are static C variables, which are shared between multiple interpreter contexts in the same process.)

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