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

INADA Naoki songofacandy at gmail.com
Fri Jul 6 13:51:41 EDT 2018


D.setdefault('c', None)
On Sat, Jul 7, 2018 at 2:49 AM Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
>
> 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
>
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
INADA Naoki  <songofacandy at gmail.com>



More information about the Python-list mailing list