Skip to content

Commit 08759ed

Browse files
committed
Fix crash in OrderedDict.setdefault when key has unstable hash
Replaced assertion with a runtime check in OrderedDict_setdefault_impl to gracefully handle keys with changing hash values. If such a key is detected, a TypeError is raised instead of aborting the interpreter.
1 parent a214db0 commit 08759ed

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

Objects/odictobject.c

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1033,7 +1033,11 @@ OrderedDict_setdefault_impl(PyODictObject *self, PyObject *key,
10331033
if (result == NULL) {
10341034
if (PyErr_Occurred())
10351035
return NULL;
1036-
assert(_odict_find_node(self, key) == NULL);
1036+
if (_odict_find_node(self, key) != NULL) {
1037+
PyErr_SetString(PyExc_RuntimeError,
1038+
"OrderedDict key appears to change its hash value over time");
1039+
return NULL;
1040+
}
10371041
if (PyODict_SetItem((PyObject *)self, key, default_value) >= 0) {
10381042
result = Py_NewRef(default_value);
10391043
}

0 commit comments

Comments
 (0)