Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 1 commit into from
Apr 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions Lib/test/test_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,15 @@ def test_context_new_1(self):
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()

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix crash when deallocating :class:`contextvars.ContextVar` with weird
unahashable string names.
13 changes: 6 additions & 7 deletions Python/context.c
Original file line number Diff line number Diff line change
Expand Up @@ -821,20 +821,19 @@ 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);

var->var_cached = NULL;
var->var_cached_tsid = 0;
var->var_cached_tsver = 0;

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)))
{
Expand Down
Loading