Thread-safe way to add a key to a dict only if it isn't already there?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Jul 6 13:45:30 EDT 2018


I have a dict with string keys:

D = {'a': None, 'b': None}

(the values don't matter for this question) and I want to add a key but 
only if it isn't already there. If I do the obvious:

if not 'c' in D:
    D['c'] = None

there's a Time Of Check to Time Of Use bug where some other thread could 
conceivably insert 'c' into the dict between the check and the insertion.

How do I do a thread-safe insertion if, and only if, the key isn't 
already there?



Thanks in advance,



-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson




More information about the Python-list mailing list