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

Devin Jeanpierre jeanpierreda at gmail.com
Sat Jul 7 11:12:16 EDT 2018


On Sat, Jul 7, 2018 at 6:49 AM Marko Rauhamaa <marko at pacujo.net> wrote:
> Is that guaranteed to be thread-safe? The documentation (<URL: http
> s://docs.python.org/3/library/stdtypes.html#dict.setdefault>) makes no
> such promise.

It's guaranteed to be thread-safe because all of Python's core
containers are thread safe (in as far as they document
behaviors/invariants, which implicitly also hold in multithreaded code
-- Python does not take the approach other languages do of
"thread-compatible" containers that have undefined behavior if mutated
from multiple threads simultaneously). It isn't guaranteed to be
_atomic_ by the documentation, but I bet no Python implementation
would make dict.setdefault non-atomic.

There's no good description of the threading rules for Python data
structures anywhere. ISTR there was a proposal to give Python some
defined rules around thread-safety a couple of years ago (to help with
things like GIL-less python projects), but I guess nothing ever came
of it.

-- Devin



More information about the Python-list mailing list