set and dict iteration

Ulrich Eckhardt ulrich.eckhardt at dominolaser.com
Fri Aug 17 07:16:05 EDT 2012


Am 17.08.2012 03:01, schrieb Paul Rubin:
> Ian Kelly <ian.g.kelly at gmail.com> writes:
>> With regard to key insertion and deletion while iterating over a dict
>> or set, though, there is just no good reason to be doing that
>> (especially as the result is very implementation-specific), and I
>> wouldn't mind a more complete low-level check against it as long as
>> it's not too expensive (which is not clearly the case with the current
>> suggestion at all).
>
> One possible approach is to freeze the dictionary against modification
> while any iterator is open on it.  You could keep a count of active
> iterators in the dict structure, adjusting it whenever an iterator is
> created or closed/destroyed.

What if there is an iterator left over from a loop that was terminated 
early? That could block access to the sequence even though nothing is 
/really/ iterating over it.

I personally prefer a reliable error, at least when __debug__ is set. 
Someone suggested a timestamp or a list of active iterators, which both 
sound reasonable. The two should be O(1) and O(#iterators) in complexity 
on all mutating operations and O(1) on iteration, so they should be 
acceptable. With a C implementation it probably boils down to very few 
cycles (checking a pointer/incrementing an integer). I can't say if this 
is feasible without compromising performance though, at the very least 
it requires an additional member in all dicts and iterators.

Uli




More information about the Python-list mailing list