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

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


Steven D'Aprano <steve+comp.lang.python at pearwood.info>:
> 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://docs.python.org/3/library/stdtypes.html#dict.setdefault>) makes no
such promise.

At least __collectios_abc.py
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'
        try:
            return self[key]
        except KeyError:
            self[key] = default
        return default

There are more such non-thread-safe definitions.


Marko



More information about the Python-list mailing list