Skip to content

Commit b3cf1f2

Browse files
[3.12] gh-132002: Fix crash of ContextVar on unhashable str subtype (GH-132003) (#132008)
gh-132002: Fix crash of `ContextVar` on unhashable `str` subtype (GH-132003) (cherry picked from commit ab2a3dd) Co-authored-by: sobolevn <mail@sobolevn.me>
1 parent afb3f33 commit b3cf1f2

File tree

3 files changed

+17
-7
lines changed

3 files changed

+17
-7
lines changed

Lib/test/test_context.py

Lines changed: 9 additions & 0 deletions
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

Lines changed: 2 additions & 0 deletions
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

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -821,20 +821,19 @@ contextvar_new(PyObject *name, PyObject *def)
821821
return NULL;
822822
}
823823

824-
var->var_hash = contextvar_generate_hash(var, name);
825-
if (var->var_hash == -1) {
826-
Py_DECREF(var);
827-
return NULL;
828-
}
829-
830824
var->var_name = Py_NewRef(name);
831-
832825
var->var_default = Py_XNewRef(def);
833826

834827
var->var_cached = NULL;
835828
var->var_cached_tsid = 0;
836829
var->var_cached_tsver = 0;
837830

831+
var->var_hash = contextvar_generate_hash(var, name);
832+
if (var->var_hash == -1) {
833+
Py_DECREF(var);
834+
return NULL;
835+
}
836+
838837
if (_PyObject_GC_MAY_BE_TRACKED(name) ||
839838
(def != NULL && _PyObject_GC_MAY_BE_TRACKED(def)))
840839
{

0 commit comments

Comments
 (0)