I'm thinking how can we implement a InsertOnlyDict
, which have the property that, if a key already exists, it can't be set to new value.
One way to implement it is to write something like:
class InsertOnlyDict(dict):
def __setitem__(self, key, value):
if key in self:
raise ....
super(InsertOnlyDict, self).__setitem__(key, value)
The method above has the problem that, if caller uses dict.__setitem__(x, k, v)
, it can still update this.
The second way to implement this is to write,
class InsertOnlyDict(object):
__slots__ = ('_internal',)
def __init__(self, *args, **kwargs):
self._internal = dict(*args, **kwargs):
def __setitem__(self, key, value):
if key in self._internal:
raise....
self._internal[key] = value
The most concern of this approach is that, this InsertOnlyDict
is no longer a dict
and can hence fails checks like isinstance(x, dict)
.
Is there any way to get around it? e.g. making a class not really using parent's class while still getting through checks like isinstance(x, dict)
?
What do you think about these approaches?