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?


On 07/06/2018 10:51 AM, INADA Naoki wrote:
 > On Sat, Jul 7, 2018 at 2:49 AM Steven D'Aprano wrote:

 >> I have a dict with string keys:
 >>
 >> --> D = {'a': None, 'b': None}

 >> How do I do a thread-safe insertion if, and only if, the key isn't
 >> already there?
 >
> D.setdefault('c', None)

This is how Enum avoids race conditions when setting up the re.RegexType enumeration.

--
~Ethan~