I'd like to subclass dict to disallow overwriting of keys, something like:
[color=blue][color=green][color=darkred]
>>> class SafeDict(dict):[/color][/color][/color]
.... def __setitem__(sel f, key, value):
.... if key in self:
.... raise KeyError('canno t 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:
[color=blue][color=green][color=darkred]
>>> SafeDict({'one' :1}, one=2)[/color][/color][/color]
{'one': 2}[color=blue][color=green][color=darkred]
>>> SafeDict([('one', 1), ('one', 2)])[/color][/color][/color]
{'one': 2}[color=blue][color=green][color=darkred]
>>> SafeDict([('one', 1), ('one', 2)], one=3)[/color][/color][/color]
{'one': 3}[color=blue][color=green][color=darkred]
>>> SafeDict(('one' , x) for x in (1, 2))[/color][/color][/color]
{'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
[color=blue][color=green][color=darkred]
>>> class SafeDict(dict):[/color][/color][/color]
.... def __setitem__(sel f, key, value):
.... if key in self:
.... raise KeyError('canno t 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:
[color=blue][color=green][color=darkred]
>>> SafeDict({'one' :1}, one=2)[/color][/color][/color]
{'one': 2}[color=blue][color=green][color=darkred]
>>> SafeDict([('one', 1), ('one', 2)])[/color][/color][/color]
{'one': 2}[color=blue][color=green][color=darkred]
>>> SafeDict([('one', 1), ('one', 2)], one=3)[/color][/color][/color]
{'one': 3}[color=blue][color=green][color=darkred]
>>> SafeDict(('one' , x) for x in (1, 2))[/color][/color][/color]
{'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
Comment