[3.13] gh-132002: Fix crash of ContextVar on unhashable str subtype (GH-132003) (#132007)

gh-132002: Fix crash of `ContextVar` on unhashable `str` subtype (GH-132003)
(cherry picked from commit ab2a3dda1d)

Co-authored-by: sobolevn <mail@sobolevn.me>
This commit is contained in:
Miss Islington (bot) 2025-04-02 14:15:44 +02:00 committed by GitHub
parent 24bee4e5cf
commit 57e4f0886d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 17 additions and 7 deletions

View file

@ -83,6 +83,15 @@ class ContextTest(unittest.TestCase):
contextvars.Context(a=1)
contextvars.Context(**{})
def test_context_new_unhashable_str_subclass(self):
# gh-132002: it used to crash on unhashable str subtypes.
class weird_str(str):
def __eq__(self, other):
pass
with self.assertRaisesRegex(TypeError, 'unhashable type'):
contextvars.ContextVar(weird_str())
def test_context_typerrors_1(self):
ctx = contextvars.Context()

View file

@ -0,0 +1,2 @@
Fix crash when deallocating :class:`contextvars.ContextVar` with weird
unahashable string names.

View file

@ -823,14 +823,7 @@ contextvar_new(PyObject *name, PyObject *def)
return NULL;
}
var->var_hash = contextvar_generate_hash(var, name);
if (var->var_hash == -1) {
Py_DECREF(var);
return NULL;
}
var->var_name = Py_NewRef(name);
var->var_default = Py_XNewRef(def);
#ifndef Py_GIL_DISABLED
@ -839,6 +832,12 @@ contextvar_new(PyObject *name, PyObject *def)
var->var_cached_tsver = 0;
#endif
var->var_hash = contextvar_generate_hash(var, name);
if (var->var_hash == -1) {
Py_DECREF(var);
return NULL;
}
if (_PyObject_GC_MAY_BE_TRACKED(name) ||
(def != NULL && _PyObject_GC_MAY_BE_TRACKED(def)))
{