<div dir="ltr">On Monday, June 4, 2018 at 11:29:15 PM UTC-7, Ben Rudiak-Gould wrote:<blockquote class="gmail_quote" style="margin: 0;margin-left: 0.8ex;border-left: 1px #ccc solid;padding-left: 1ex;">One example (or family of examples) is any situation where you would
<br>have a UNIQUE constraint on an indexed column in a database. If the
<br>values in a column should always be distinct, like the usernames in a
<br>table of user accounts, you can declare that column UNIQUE (or PRIMARY
<br>KEY) and any attempt to add a record with a duplicate username will
<br>fail.<br></blockquote><div><br></div><div><br></div>This might do the trick for you:<div><br></div><div><div>    class InsertOnlyDict(dict):</div><div>        '''</div><div>        Supports item inserts, but not updates.</div><div>        '''</div><div><br></div><div>        def __init__(self, *args, **kwds):</div><div>            self.update(*args, **kwds)</div><div><br></div><div>        def __setitem__(self, key, value):</div><div>            if key in self:</div><div>                raise KeyError(f'Duplicate key, {key!r}')</div><div>            super().__setitem__(key, value)</div><div><br></div><div>        def update(self, *args, **kwds):</div><div>            for k, v in dict(*args, **kwds).items():</div><div>                self[k] = v</div></div><div><br></div><div><br></div><div>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. </div></div>