S
Steven Bethard
I'd like to subclass dict to disallow overwriting of keys, something like:
.... 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:
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
.... 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:
{'one': 2}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))
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