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

Marko Rauhamaa marko at
Sat Jul 7 09:41:31 EDT 2018

Steven D'Aprano <steve+comp.lang.python at>:
> On Sat, 07 Jul 2018 02:51:41 +0900, INADA Naoki wrote:
>> D.setdefault('c', None)
> Oh that's clever!

Is that guaranteed to be thread-safe? The documentation (<URL: http
s://>) makes no
such promise.

At least
contains this method definition for MutableMapping:

    def setdefault(self, key, default=None):
        'D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D'
            return self[key]
        except KeyError:
            self[key] = default
        return default

There are more such non-thread-safe definitions.


More information about the Python-list mailing list