diff -r 34460219c0e0 Lib/test/test_dict.py --- a/Lib/test/test_dict.py Fri Jul 03 00:41:16 2015 -0400 +++ b/Lib/test/test_dict.py Sat Jul 04 10:27:11 2015 -0500 @@ -932,16 +932,31 @@ class DictTest(unittest.TestCase): d.clear() self.check_reentrant_insertion(mutate) def mutate(d): while d: d.popitem() self.check_reentrant_insertion(mutate) + def test_merge_and_mutate(self): + class X: + def __hash__(self): + return 0 + + def __eq__(self, o): + other.clear() + return False + + l = [(i,0) for i in range(1, 1337)] + other = dict(l) + other[X()] = 0 + d = {X(): 0, 1: 1} + self.assertRaises(RuntimeError, d.update, other) + from test import mapping_tests class GeneralMappingTests(mapping_tests.BasicTestMappingProtocol): type2test = dict class Dict(dict): pass diff -r 34460219c0e0 Objects/dictobject.c --- a/Objects/dictobject.c Fri Jul 03 00:41:16 2015 -0400 +++ b/Objects/dictobject.c Sat Jul 04 10:27:11 2015 -0500 @@ -1968,30 +1968,42 @@ PyDict_Merge(PyObject *a, PyObject *b, i /* Do one big resize at the start, rather than * incrementally resizing as we insert new items. Expect * that there will be no (or few) overlapping keys. */ if (mp->ma_keys->dk_usable * 3 < other->ma_used * 2) if (dictresize(mp, (mp->ma_used + other->ma_used)*2) != 0) return -1; for (i = 0, n = DK_SIZE(other->ma_keys); i < n; i++) { - PyObject *value; + PyObject *key, *value; + Py_hash_t hash; entry = &other->ma_keys->dk_entries[i]; + key = entry->me_key; + hash = entry->me_hash; if (other->ma_values) value = other->ma_values[i]; else value = entry->me_value; - if (value != NULL && - (override || - PyDict_GetItem(a, entry->me_key) == NULL)) { - if (insertdict(mp, entry->me_key, - entry->me_hash, - value) != 0) + if (value != NULL) { + int err = 0; + Py_INCREF(key); + Py_INCREF(value); + if (override || PyDict_GetItem(a, key) == NULL) + err = insertdict(mp, key, hash, value); + Py_DECREF(value); + Py_DECREF(key); + if (err != 0) return -1; + + if (n != DK_SIZE(other->ma_keys)) { + PyErr_SetString(PyExc_RuntimeError, + "dict mutated during update"); + return -1; + } } } } else { /* Do it the generic, slower way */ PyObject *keys = PyMapping_Keys(b); PyObject *iter; PyObject *key, *value;