Reputation: 205
If d
is a dictionary, then apparently CPython does not like it if another thread modifies d while
[k for k in d]
is evaluated. How about using
list(d)
instead? Is this thread-safe?
Upvotes: 2
Views: 163
Reputation:
I'm fully with @user2357112, this is an implementation detail and you should not rely on it. But for the sake of answering the question: The relevant list
and dict
methods are written in C, hence the call is a single bytecode operation, and the code does not release the GIL directly or indirectly, as far as I can tell. Therefore in current CPython no other Python thread can interrupt the list
call and modify d
.
Note that this breaks down if either list
has been replaced with something else, or d
is not an actual honest-to-god dictobject
written in C. Also note that "is written in C" is not a sufficient condition, for example many collection operations call comparison/hashing methods and thus execute arbitrary Python code, allowing the GIL to be released.
Upvotes: 6