Skip to content

Commit 57e4f08

Browse files
[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 ab2a3dd) Co-authored-by: sobolevn <[email protected]>
1 parent 24bee4e commit 57e4f08

File tree

3 files changed

+17
-7
lines changed

3 files changed

+17
-7
lines changed

Lib/test/test_context.py

+9
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,15 @@ def test_context_new_1(self):
8383
contextvars.Context(a=1)
8484
contextvars.Context(**{})
8585

86+
def test_context_new_unhashable_str_subclass(self):
87+
# gh-132002: it used to crash on unhashable str subtypes.
88+
class weird_str(str):
89+
def __eq__(self, other):
90+
pass
91+
92+
with self.assertRaisesRegex(TypeError, 'unhashable type'):
93+
contextvars.ContextVar(weird_str())
94+
8695
def test_context_typerrors_1(self):
8796
ctx = contextvars.Context()
8897

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.

Python/context.c

+6-7
Original file line numberDiff line numberDiff line change
@@ -823,14 +823,7 @@ contextvar_new(PyObject *name, PyObject *def)
823823
return NULL;
824824
}
825825

826-
var->var_hash = contextvar_generate_hash(var, name);
827-
if (var->var_hash == -1) {
828-
Py_DECREF(var);
829-
return NULL;
830-
}
831-
832826
var->var_name = Py_NewRef(name);
833-
834827
var->var_default = Py_XNewRef(def);
835828

836829
#ifndef Py_GIL_DISABLED
@@ -839,6 +832,12 @@ contextvar_new(PyObject *name, PyObject *def)
839832
var->var_cached_tsver = 0;
840833
#endif
841834

835+
var->var_hash = contextvar_generate_hash(var, name);
836+
if (var->var_hash == -1) {
837+
Py_DECREF(var);
838+
return NULL;
839+
}
840+
842841
if (_PyObject_GC_MAY_BE_TRACKED(name) ||
843842
(def != NULL && _PyObject_GC_MAY_BE_TRACKED(def)))
844843
{

0 commit comments

Comments
 (0)