[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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

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'
            return self[key]
        except KeyError:
            self[key] = default
        return default

There are more such non-thread-safe definitions.