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.
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.
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.
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.
Most Dictionary Operations Are AtomicMany common operations on a dict are atomic, meaning that they are thread-safe.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With