sublcassing dict without losing functionality

Steven Bethard steven.bethard at gmail.com
Mon Nov 1 15:32:04 EST 2004


I'd like to subclass dict to disallow overwriting of keys, something like:

>>> class SafeDict(dict):
...    def __setitem__(self, key, value):
...        if key in self:
...            raise KeyError('cannot assign value %r to key %r, value %r'
...                           'already exists' % (value, key, self[key]))
...        super(SafeDict, self).__setitem__(key, value)
...        

The problem is, dict doesn't appear to call __setitem__ in any of the
__init__ forms, so none of the following raise errors as I'd like them
to:

>>> SafeDict({'one':1}, one=2)
{'one': 2}
>>> SafeDict([('one', 1), ('one', 2)])
{'one': 2}
>>> SafeDict([('one', 1), ('one', 2)], one=3)
{'one': 3}
>>> SafeDict(('one', x) for x in (1, 2))
{'one': 2}

etc.  Is there a simple way to override this behavior in dict without
having to rewrite __init__?  There are so many cases in dict.__init__
that I'm hesitant to try to reproduce them all...

Steve
-- 
You can wordify anything if you just verb it.
        - Bucky Katt, Get Fuzzy



More information about the Python-list mailing list