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

Marko Rauhamaa marko at
Sun Jul 8 15:18:20 EDT 2018

Chris Angelico <rosuav at>:
> Are you assuming that Python's semantics are defined by the semantics
> of one possible implementation language?

What are Python's semantics defined by? I've been using these:



Unfortunately, neither spec says anything about the atomicity of

Therefore, the application programmer must assume it is not atomic. In
fact, as brought up in this discussion, the consultation of
object.__hash__() and object.__eq__() almost guarantee the
*non*-atomicity of dict.setdefault().


More information about the Python-list mailing list