gh-132825: Enhance unhashable error messages for dict and set (#132828)

This commit is contained in:
Victor Stinner 2025-04-23 17:10:09 +02:00 committed by GitHub
parent b2e666f30a
commit 426449d983
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 136 additions and 14 deletions

View file

@ -211,11 +211,28 @@ set_add_entry(PySetObject *so, PyObject *key, Py_hash_t hash)
return set_add_entry_takeref(so, Py_NewRef(key), hash);
}
static void
set_unhashtable_type(PyObject *key)
{
PyObject *exc = PyErr_GetRaisedException();
assert(exc != NULL);
if (!Py_IS_TYPE(exc, (PyTypeObject*)PyExc_TypeError)) {
PyErr_SetRaisedException(exc);
return;
}
PyErr_Format(PyExc_TypeError,
"cannot use '%T' as a set element (%S)",
key, exc);
Py_DECREF(exc);
}
int
_PySet_AddTakeRef(PySetObject *so, PyObject *key)
{
Py_hash_t hash = _PyObject_HashFast(key);
if (hash == -1) {
set_unhashtable_type(key);
Py_DECREF(key);
return -1;
}
@ -384,6 +401,7 @@ set_add_key(PySetObject *so, PyObject *key)
{
Py_hash_t hash = _PyObject_HashFast(key);
if (hash == -1) {
set_unhashtable_type(key);
return -1;
}
return set_add_entry(so, key, hash);
@ -394,6 +412,7 @@ set_contains_key(PySetObject *so, PyObject *key)
{
Py_hash_t hash = _PyObject_HashFast(key);
if (hash == -1) {
set_unhashtable_type(key);
return -1;
}
return set_contains_entry(so, key, hash);
@ -404,6 +423,7 @@ set_discard_key(PySetObject *so, PyObject *key)
{
Py_hash_t hash = _PyObject_HashFast(key);
if (hash == -1) {
set_unhashtable_type(key);
return -1;
}
return set_discard_entry(so, key, hash);