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

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


Chris Angelico <rosuav at gmail.com>:
> 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:

   <URL: https://docs.python.org/3/reference/>

   <URL: https://docs.python.org/3/library/>

Unfortunately, neither spec says anything about the atomicity of
dict.setdefault().

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().


Marko


More information about the Python-list mailing list