Skip to content

Commit ab2a3dd

Browse files
authored
gh-132002: Fix crash of ContextVar on unhashable str subtype (#132003)
1 parent 87d9983 commit ab2a3dd

File tree

3 files changed

+17
-7
lines changed

3 files changed

+17
-7
lines changed

Diff for: Lib/test/test_context.py

+9
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,15 @@ def test_context_new_1(self):
9292
contextvars.Context(a=1)
9393
contextvars.Context(**{})
9494

95+
def test_context_new_unhashable_str_subclass(self):
96+
# gh-132002: it used to crash on unhashable str subtypes.
97+
class weird_str(str):
98+
def __eq__(self, other):
99+
pass
100+
101+
with self.assertRaisesRegex(TypeError, 'unhashable type'):
102+
contextvars.ContextVar(weird_str())
103+
95104
def test_context_typerrors_1(self):
96105
ctx = contextvars.Context()
97106

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

Diff for: Python/context.c

+6-7
Original file line numberDiff line numberDiff line change
@@ -878,14 +878,7 @@ contextvar_new(PyObject *name, PyObject *def)
878878
return NULL;
879879
}
880880

881-
var->var_hash = contextvar_generate_hash(var, name);
882-
if (var->var_hash == -1) {
883-
Py_DECREF(var);
884-
return NULL;
885-
}
886-
887881
var->var_name = Py_NewRef(name);
888-
889882
var->var_default = Py_XNewRef(def);
890883

891884
#ifndef Py_GIL_DISABLED
@@ -894,6 +887,12 @@ contextvar_new(PyObject *name, PyObject *def)
894887
var->var_cached_tsver = 0;
895888
#endif
896889

890+
var->var_hash = contextvar_generate_hash(var, name);
891+
if (var->var_hash == -1) {
892+
Py_DECREF(var);
893+
return NULL;
894+
}
895+
897896
if (_PyObject_GC_MAY_BE_TRACKED(name) ||
898897
(def != NULL && _PyObject_GC_MAY_BE_TRACKED(def)))
899898
{

0 commit comments

Comments
 (0)