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. 
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to