Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Python's dict.pop atomic?

It seems reasonable to believe that dict.pop operates atomically, since it raises KeyError if the specified key is missing and no default is provided, like so:

d.pop(k)

However, the documentation does not appear to specifically address that point, at least not in the section specifically documenting dict.pop.

This question occurred to me as I was reviewing an answer of mine which used this pattern:

if k in d: del d[k]

At the time, I was not thinking of the potential condition that a key may be present during the if, but not at the time of del. If dict.pop does indeed provide an atomic alternative, then I should note that in my answer.

like image 788
zigg Avatar asked Jun 26 '13 16:06

zigg


People also ask

Are Python dictionaries Atomic?

While Python's built-in data types such as dictionaries appear to have atomic operations, there are corner cases where they aren't atomic (e.g. if __hash__ or __eq__ are implemented as Python methods) and their atomicity should not be relied upon.

Does pop work on dict?

The pop() method removes the specified item from the dictionary. The value of the removed item is the return value of the pop() method, see example below.

Can we use pop in dictionary Python?

Yes, the Python pop dictionary method is an in-built function that allows you to remove/pop items from a dictionary. It removes items based on the key you specify in the parameters while returning the value of that key.

Are Dictionaries Threadsafe Python?

Most Dictionary Operations Are AtomicMany common operations on a dict are atomic, meaning that they are thread-safe.


1 Answers

For the default type, dict.pop() is a C-function call, which means that it is executed with one bytecode evaluation. This makes that call atomic.

Python threads switch only when the bytecode evaluation loop lets them, so at bytecode boundaries. Some Python C functions do call back into Python code (think __dunder__ special method hooks), but the dict.pop() method does not, at least not for the default dict type.

like image 127
Martijn Pieters Avatar answered Oct 01 '22 16:10

Martijn Pieters