assigning a custom mapping type to __dict__

Daniel Cer Daniel.Cer at cs.colorado.edu
Tue Mar 1 04:06:25 EST 2005


Why not just inherit from dict? That seems to work.

 >>> class M(dict):
...   def __getitem__(self,key):
...     return 42
...   def __setitem__(self,key,value):
...     pass
...
 >>> class C(object):
...    pass
...
 >>> c = C()
 >>> c.__dict__ = M()
 >>> c.__dict__['x']
42

-Dan

Steven Bethard wrote:

> I tried to Google for past discussion on this topic, but without much 
> luck.  If this has been discussed before, I'd be grateful for a pointer.
>
> Does anyone know why you can't assign a custom mapping type to an 
> object's __dict__?
>
> py> class M(object):
> ...     def __getitem__(self, key):
> ...         return 42
> ...     def __setitem__(self, key, value):
> ...         pass
> ...
> py> class C(object):
> ...     pass
> ...
> py> c = C()
> py> c.__dict__ = M()
> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
> TypeError: __dict__ must be set to a dictionary
>
> I looked at the source in typeobject.c (where this error originates), 
> but I'm not fluent enough in CPython yet to be able to tell why a true 
> dict type is preferred here over just a mapping type...
>
> STeVe





More information about the Python-list mailing list