set and dict iteration

Dave Angel d at davea.name
Thu Aug 16 15:49:39 EDT 2012


On 08/16/2012 02:00 PM, Aaron Brady wrote:
> Hello,
>
> I observed an inconsistency in the behavior of 'set' and 'dict' iterators.  It is "by design" according to the docs.
>
> '''
> http://docs.python.org/dev/library/stdtypes.html#dict-views
>
> iter(dictview).  Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries.
> '''
>
> The 'set' has the same behavior.  Iteration might also complete successfully.
>
> The inconsistency is, if we remove an element from a set and add another during iteration, the new element might appear later in the iteration, and might not, depending on the hash code; therefore comparing the size of the set between iterations isn't adequate.  Example:
> <SNIP>
>
>
> Iteration should behave the same regardless of the contents of the set.  Continuing iteration over sets and dicts after a modification isn't defined; it should unconditionally raise an error.

Why is it the iterator's job to protect against the user's  bug?  The
doc is clear enough.  If you don't change the collection, you won't have
a problem.

> <SNIP more details>.

Everything else is implementation defined.  Why should an implementation
be forced to have ANY extra data structure to detect a static bug in the
caller's code?



-- 

DaveA




More information about the Python-list mailing list