Safely add a key to a dict only if it does not already exist?

Lie Ryan lie.1296 at gmail.com
Sat Jan 19 00:00:25 EST 2013


On 19/01/13 15:15, Chris Rebert wrote:
> On Friday, January 18, 2013, Steven D'Aprano wrote:
>
>     I wish to add a key to a dict only if it doesn't already exist, but
>     do it
>     in a thread-safe manner.
>
>     The naive code is:
>
>     if key not in dict:
>          dict[key] = value
>
>
>     but of course there is a race condition there: it is possible that
>
>     another thread may have added the same key between the check and the
>     store.
>
>     How can I add a key in a thread-safe manner?
>
>
> I'm not entirely sure, but have you investigated dict.setdefault() ?

dict.setdefault() was not atomic on older python version, they were made 
atomic in Python 2.7.3 and Python 3.2.3.

See bug13521 in the issue tracker http://bugs.python.org/issue13521

PS: The bug tracker seems down at the moment, so pulled this from 
Google's cache:
https://webcache.googleusercontent.com/search?q=cache:59PO_F-VEfwJ:bugs.python.org/issue13521+&cd=1&hl=en&ct=clnk&client=ubuntu




More information about the Python-list mailing list