Unexpected behavior of read only attributes and super

Steven Bethard steven.bethard at gmail.com
Tue Dec 6 22:53:11 EST 2005


Samuel M. Smith wrote:
> The dict class has some read only attributes that generate an  exception 
> if I try to assign a value to them.
> I wanted to trap for this exception in a subclass using super but it  
> doesn't happen.
> 
> class SD(dict):
>    pass
> 
[snip]
> s = SD()
> super(SD,s).__setattr__('__iter__', True)
> 
> Expecting to get the ReadOnly exception but I don't get the exception.

Note that __iter__ is on the dict *type* not dict instances.  Try this:

py> class SD(dict):
...     pass
...
py> super(SD, SD).__init__ = False
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
AttributeError: 'super' object attribute '__init__' is read-only

You can always shadow class-level attributes in the instance dict. 
(That's what you were doing.)  If you want to (try to) replace an 
attribute in the class dict, you need to use the class object, not an 
instance object.

HTH,

STeVe



More information about the Python-list mailing list