Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions Lib/test/test_ordered_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -1014,6 +1014,28 @@ def test_weakref_list_is_not_traversed(self):

gc.collect()

def test_pop_inconsistent_eq(self):
class K:
def __init__(self):
self.calls = 0

def __hash__(self):
return 12345

# Behave inconsistently across repeated equality checks.
def __eq__(self, other):
self.calls += 1
return self.calls <= 2

k1 = K()
k2 = K()

od = self.OrderedDict()
od[k1] = "value"

with self.assertRaises(KeyError):
od.pop(k2)


class PurePythonOrderedDictSubclassTests(PurePythonOrderedDictTests):

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Fix a crash in collections.OrderedDict.pop() when a key's __eq__
implementation returns inconsistent results across repeated comparisons.
OrderedDict.pop() now raises KeyError instead of crashing when no default
value is provided.
7 changes: 6 additions & 1 deletion Objects/odictobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -1095,7 +1095,12 @@ _odict_popkey_hash(PyObject *od, PyObject *key, PyObject *failobj,
/* Now delete the value from the dict. */
if (_PyDict_Pop_KnownHash((PyDictObject *)od, key, hash,
&value) == 0) {
value = Py_NewRef(failobj);
if (failobj) {
value = Py_NewRef(failobj);
}
else {
PyErr_SetObject(PyExc_KeyError, key);
}
}
}
else if (value == NULL && !PyErr_Occurred()) {
Expand Down
Loading