Skip to content

Commit 482fad7

Browse files
gh-108295: Fix crashes with TypeVar weakrefs (#108517)
1 parent 2b15536 commit 482fad7

File tree

3 files changed

+14
-0
lines changed

3 files changed

+14
-0
lines changed

Lib/test/test_typing.py

+10
Original file line numberDiff line numberDiff line change
@@ -544,6 +544,16 @@ def test_bad_var_substitution(self):
544544
with self.assertRaises(TypeError):
545545
list[T][arg]
546546

547+
def test_many_weakrefs(self):
548+
# gh-108295: this used to segfault
549+
for cls in (ParamSpec, TypeVarTuple, TypeVar):
550+
with self.subTest(cls=cls):
551+
vals = weakref.WeakValueDictionary()
552+
553+
for x in range(100000):
554+
vals[x] = cls(str(x))
555+
del vals
556+
547557

548558
def template_replace(templates: list[str], replacements: dict[str, list[str]]) -> list[tuple[str]]:
549559
"""Renders templates with possible combinations of replacements.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix crashes related to use of weakrefs on :data:`typing.TypeVar`.

Objects/typevarobject.c

+3
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,7 @@ typevar_dealloc(PyObject *self)
201201
Py_XDECREF(tv->constraints);
202202
Py_XDECREF(tv->evaluate_constraints);
203203
_PyObject_ClearManagedDict(self);
204+
PyObject_ClearWeakRefs(self);
204205

205206
Py_TYPE(self)->tp_free(self);
206207
Py_DECREF(tp);
@@ -743,6 +744,7 @@ paramspec_dealloc(PyObject *self)
743744
Py_DECREF(ps->name);
744745
Py_XDECREF(ps->bound);
745746
_PyObject_ClearManagedDict(self);
747+
PyObject_ClearWeakRefs(self);
746748

747749
Py_TYPE(self)->tp_free(self);
748750
Py_DECREF(tp);
@@ -1022,6 +1024,7 @@ typevartuple_dealloc(PyObject *self)
10221024

10231025
Py_DECREF(tvt->name);
10241026
_PyObject_ClearManagedDict(self);
1027+
PyObject_ClearWeakRefs(self);
10251028

10261029
Py_TYPE(self)->tp_free(self);
10271030
Py_DECREF(tp);

0 commit comments

Comments
 (0)