[Python-Dev] Bug or not? Different behaviour iterating list andcollections.deque

Raymond Hettinger python at rcn.com
Mon Jan 8 18:16:20 CET 2007


"Christos Georgiou"
> In retrospection, the example code I chose, although it showed the two
> issues I thought important ('list / deque iteration discrepancy' and 'empty 
> / non-empty deque iteration discrepancy') was not as plain as needed, ...

Lists are unique in the way they allow mutation during iteration because
indexed lookup allows for a meaningful definition of what should be
done as the list mutates.

In contrast, deques are more like dictionaries and should not be mutated
during iteration.  The issue is that a deque could be so substantially
modified that there is not a clear, meaningful, and useful definition of what
item should be next served-up.

With respect to the second question, please assign an SF report to me
and I'll look at it in detail when I have time.  It appears to be an
idiosyncracy resulting from the ordering of the test for StopIteration
versus the test for RuntimeError.  The question is whether I can swap
the test order without introducing other anomalies.

Raymond



P.S.  The patch would look like this:

Index: collectionsmodule.c
===================================================================
--- collectionsmodule.c (revision 53281)
+++ collectionsmodule.c (working copy)
@@ -911,15 +911,14 @@
 {
        PyObject *item;

-       if (it->counter == 0)
-               return NULL;
-
        if (it->deque->state != it->state) {
                it->counter = 0;
                PyErr_SetString(PyExc_RuntimeError,
                                "deque mutated during iteration");
                return NULL;
        }
+       if (it->counter == 0)
+               return NULL;
        assert (!(it->b == it->deque->rightblock &&
                  it->index > it->deque->rightindex));


More information about the Python-Dev mailing list