From b952ab43f281bafd8d4fce4e84b41e655a3e7c23 Mon Sep 17 00:00:00 2001 From: Eric Snow Date: Mon, 1 Jun 2015 23:35:13 -0600 Subject: [PATCH] Issue #24359: Check for changed OrderedDict size during iteration. --- Lib/test/test_collections.py | 4 ---- Misc/NEWS | 2 ++ Objects/odictobject.c | 10 ++++++++++ 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/Lib/test/test_collections.py b/Lib/test/test_collections.py index 097aa9afeae..7a1ff14b172 100644 --- a/Lib/test/test_collections.py +++ b/Lib/test/test_collections.py @@ -1746,10 +1746,6 @@ class OrderedDictTests: self.assertEqual(list(reversed(od.items())), list(reversed(pairs))) def test_detect_deletion_during_iteration(self): - # XXX This test should also work under cOrderedDict. - if self.module is c_coll: - raise unittest.SkipTest("only valid for pure Python OrderedDict") - OrderedDict = self.module.OrderedDict od = OrderedDict.fromkeys('abc') it = iter(od) diff --git a/Misc/NEWS b/Misc/NEWS index 75186c86e7d..c0990ce531d 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -19,6 +19,8 @@ Library - Issue #24348: Drop superfluous incref/decref. +- Issue #24359: Check for changed OrderedDict size during iteration. + What's New in Python 3.5.0 beta 2? ================================== diff --git a/Objects/odictobject.c b/Objects/odictobject.c index b91bd680bad..b44a61ef75a 100644 --- a/Objects/odictobject.c +++ b/Objects/odictobject.c @@ -1796,6 +1796,7 @@ typedef struct { PyObject_HEAD int kind; PyODictObject *di_odict; + Py_ssize_t di_size; PyObject *di_current; PyObject *di_result; /* reusable result tuple for iteritems */ } odictiterobject; @@ -1835,6 +1836,14 @@ odictiter_nextkey(odictiterobject *di) if (di->di_current == NULL) goto done; /* We're already done. */ + /* Check for unsupported changes. */ + if (di->di_size != PyODict_SIZE(di->di_odict)) { + PyErr_SetString(PyExc_RuntimeError, + "OrderedDict changed size during iteration"); + di->di_size = -1; /* Make this state sticky */ + return NULL; + } + /* Get the key. */ node = _odict_find_node(di->di_odict, di->di_current); if (node == NULL) { @@ -2033,6 +2042,7 @@ odictiter_new(PyODictObject *od, int kind) node = reversed ? _odict_LAST(od) : _odict_FIRST(od); di->di_current = node ? _odictnode_KEY(node) : NULL; Py_XINCREF(di->di_current); + di->di_size = PyODict_SIZE(od); di->di_odict = od; Py_INCREF(od);