Skip to content

Commit 0268b07

Browse files
gh-119180: Disallow instantiation of ConstEvaluator objects (#124561)
1 parent ffdc80e commit 0268b07

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

Lib/test/test_type_params.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1452,3 +1452,14 @@ def f[T: (int, str)](): pass
14521452
self.assertEqual(annotationlib.call_evaluate_function(case.evaluate_constraints, annotationlib.Format.VALUE), (int, str))
14531453
self.assertEqual(annotationlib.call_evaluate_function(case.evaluate_constraints, annotationlib.Format.FORWARDREF), (int, str))
14541454
self.assertEqual(annotationlib.call_evaluate_function(case.evaluate_constraints, annotationlib.Format.SOURCE), '(int, str)')
1455+
1456+
def test_const_evaluator(self):
1457+
T = TypeVar("T", bound=int)
1458+
self.assertEqual(repr(T.evaluate_bound), "<constevaluator <class 'int'>>")
1459+
1460+
ConstEvaluator = type(T.evaluate_bound)
1461+
1462+
with self.assertRaisesRegex(TypeError, r"cannot create '_typing\._ConstEvaluator' instances"):
1463+
ConstEvaluator() # This used to segfault.
1464+
with self.assertRaisesRegex(TypeError, r"cannot set 'attribute' attribute of immutable type '_typing\._ConstEvaluator'"):
1465+
ConstEvaluator.attribute = 1

Objects/typevarobject.c

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ constevaluator_clear(PyObject *self)
151151
}
152152

153153
static PyObject *
154-
constevaluator_repr(PyObject *self, PyObject *repr)
154+
constevaluator_repr(PyObject *self)
155155
{
156156
PyObject *value = ((constevaluatorobject *)self)->value;
157157
return PyUnicode_FromFormat("<constevaluator %R>", value);
@@ -242,7 +242,8 @@ static PyType_Slot constevaluator_slots[] = {
242242
PyType_Spec constevaluator_spec = {
243243
.name = "_typing._ConstEvaluator",
244244
.basicsize = sizeof(constevaluatorobject),
245-
.flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE,
245+
.flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE
246+
| Py_TPFLAGS_DISALLOW_INSTANTIATION,
246247
.slots = constevaluator_slots,
247248
};
248249

0 commit comments

Comments
 (0)