class InsertOnlyDict(dict):
'''
Supports item inserts, but not updates.
'''
def __init__(self, *args, **kwds):
self.update(*args, **kwds)
def __setitem__(self, key, value):
if key in self:
raise KeyError(f'Duplicate key, {key!r}')
super().__setitem__(key, value)
def update(self, *args, **kwds):
for k, v in dict(*args, **kwds).items():
self[k] = v
If you're using a dict-like as an interface to a database table with a unique key constraint, I think your database will appropriately raise IntegrityError when you accidentally try to update instead of insert.