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

Roy Smith roy at panix.com
Sat Jan 19 08:04:15 EST 2013


In article <50fa1bf1$0$30003$c3e8da3$5496439d at news.astraweb.com>,
 Steven D'Aprano <steve+comp.lang.python at pearwood.info> 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?

You want something along the lines of:

from threading import Lock
lock = Lock()
[...]
lock.acquire()
if key not in dict:
   dict[key] = value
lock.release()

You probably want to wrap that up in a context manager to ensure the 
lock is released if you get an exception.  You don't want your entire 
program to hang just because somebody handed you a key which wasn't 
hashable, for example.



More information about the Python-list mailing list