[Python-ideas] Add dict.append and dict.extend
Michael Selik
mike at selik.org
Fri Jun 8 19:38:05 EDT 2018
On Monday, June 4, 2018 at 11:29:15 PM UTC-7, Ben Rudiak-Gould wrote:
>
> One example (or family of examples) is any situation where you would
> have a UNIQUE constraint on an indexed column in a database. If the
> values in a column should always be distinct, like the usernames in a
> table of user accounts, you can declare that column UNIQUE (or PRIMARY
> KEY) and any attempt to add a record with a duplicate username will
> fail.
>
This might do the trick for you:
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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180608/0eeeaaf5/attachment.html>
More information about the Python-ideas
mailing list