gh-119180: Disallow instantiation of ConstEvaluator objects (#124561)

This commit is contained in:
Jelle Zijlstra 2024-09-25 16:30:17 -07:00 committed by GitHub
parent ffdc80e93d
commit 0268b072d8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 14 additions and 2 deletions

View File

@ -1452,3 +1452,14 @@ class TestEvaluateFunctions(unittest.TestCase):
self.assertEqual(annotationlib.call_evaluate_function(case.evaluate_constraints, annotationlib.Format.VALUE), (int, str)) self.assertEqual(annotationlib.call_evaluate_function(case.evaluate_constraints, annotationlib.Format.VALUE), (int, str))
self.assertEqual(annotationlib.call_evaluate_function(case.evaluate_constraints, annotationlib.Format.FORWARDREF), (int, str)) self.assertEqual(annotationlib.call_evaluate_function(case.evaluate_constraints, annotationlib.Format.FORWARDREF), (int, str))
self.assertEqual(annotationlib.call_evaluate_function(case.evaluate_constraints, annotationlib.Format.SOURCE), '(int, str)') self.assertEqual(annotationlib.call_evaluate_function(case.evaluate_constraints, annotationlib.Format.SOURCE), '(int, str)')
def test_const_evaluator(self):
T = TypeVar("T", bound=int)
self.assertEqual(repr(T.evaluate_bound), "<constevaluator <class 'int'>>")
ConstEvaluator = type(T.evaluate_bound)
with self.assertRaisesRegex(TypeError, r"cannot create '_typing\._ConstEvaluator' instances"):
ConstEvaluator() # This used to segfault.
with self.assertRaisesRegex(TypeError, r"cannot set 'attribute' attribute of immutable type '_typing\._ConstEvaluator'"):
ConstEvaluator.attribute = 1

View File

@ -151,7 +151,7 @@ constevaluator_clear(PyObject *self)
} }
static PyObject * static PyObject *
constevaluator_repr(PyObject *self, PyObject *repr) constevaluator_repr(PyObject *self)
{ {
PyObject *value = ((constevaluatorobject *)self)->value; PyObject *value = ((constevaluatorobject *)self)->value;
return PyUnicode_FromFormat("<constevaluator %R>", value); return PyUnicode_FromFormat("<constevaluator %R>", value);
@ -242,7 +242,8 @@ static PyType_Slot constevaluator_slots[] = {
PyType_Spec constevaluator_spec = { PyType_Spec constevaluator_spec = {
.name = "_typing._ConstEvaluator", .name = "_typing._ConstEvaluator",
.basicsize = sizeof(constevaluatorobject), .basicsize = sizeof(constevaluatorobject),
.flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE, .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE
| Py_TPFLAGS_DISALLOW_INSTANTIATION,
.slots = constevaluator_slots, .slots = constevaluator_slots,
}; };