cannot create my own dict

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Wed Sep 19 15:43:59 EDT 2007


A.T.Hofkamp a écrit :
> Hello all,
> 
> This morning I tried to create my own read-only dictionary, and failed
> miserably.
> I don't understand why, can somebody enlighten me?
> 
(snip)

> So if copying all methods of a native dictionary is not enough, what should I
> do to make my class work as a dictionary WITHOUT deriving from dict (which will
> obviously work).
> 

Sorry, I missed this last requirement. BTW, why don't you want to 
subclass dict ?

Anyway, something like the following should do the trick
(NB : Q&D, needs at least some testing):

class ReadOnlyDict(object):
     def __init__(self, *args, **kw):
         self._dict = dict(*args, **kw)

     def __getattr__(self, name):
         if name in ('__setitem__', 'setdefault'):
             raise AttributeError("%s is read-only" % \
                                   self.__class__.__name__)
         return getattr(self._dict, name)

     for name in dir(dict):
         if name.startswith('__') \
         and name not in ('__new__', '__init__',
                          '__setitem__', '__class__', '__dict__'):
             exec("%s = dict.%s" % (name, name))







More information about the Python-list mailing list