[Python-Dev] Issue 19332: Guard against changing dict during iteration

Antoine Pitrou solipsis at pitrou.net
Wed Nov 6 18:16:59 CET 2013


Le 06/11/2013 06:41, Nick Coghlan a écrit :
>
> The behaviour of mutating builtin containers while iterating over them
> is formally undefined beyond "it won't segfault" (one of the few such
> undefined behaviours in Python). The associated exceptions are thus
> strictly "best effort given other constraints".

Not sure what you mean with "formally undefined". For example, you can 
perfectly well change a list's contents while iterating over it, and I 
bet there's a lot of code that relies on that, as in::

for i, value in enumerate(mylist):
     if some_condition(value):
         mylist[i] = some_function(value)

If you change "builtin containers" to "builtin unordered containers", 
then you probably are closer to the truth :)

>  >or perhaps some performance measurements that would show there is no
> performance based reason to not have the patch added.  (I can try to do
> the performance part myself if necessary, I'm just not sure what all the
> steps are yet.)
>
> If the benchmark suite indicates there's no measurable speed penalty
> then such a patch may be worth reconsidering. I'd be astonished if that
> was actually the case, though - the lowest impact approach I can think
> of is to check for live iterators when setting a dict entry, and that
> still has non-trivial size and speed implications.

I think Serhiy's patch is much simpler than that (is it Serhiy's? I 
think so).

Regards

Antoine.




More information about the Python-Dev mailing list