本文介绍了Python的dict.pop是原子吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎有理由相信以原子方式运行,因为如果指定的键丢失并且没有提供默认值,则它会引发 KeyError

d.pop(k)

但是,该文档似乎并没有具体说明这一点,至少在本节不具体记录 dict.pop

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]

当时,我并没有想到在中如果可能存在密钥的潜在条件,而不是在德尔。如果 dict.pop 确实提供了一个原子替代方法,那么我应该注意到在我的答案中。

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.

推荐答案

对于默认类型, dict.pop()是一个C函数调用,这意味着它使用一个字节码评估。这使得该调用成为原子。

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线程才会切换,因此在字节码边界处。一些Python C函数会调用Python代码(认为 __ dunder __ 特殊方法钩子),但是 dict.pop()方法没有,至少不是默认的 dict 类型。

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.

这篇关于Python的dict.pop是原子吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:38