osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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


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