Skip to content

Commit d2a536b

Browse files
gh-110782: Fix crash when TypeVar is constructed with keyword args (#110784)
1 parent 2c472a8 commit d2a536b

File tree

3 files changed

+28
-18
lines changed

3 files changed

+28
-18
lines changed

Lib/test/test_typing.py

+6
Original file line numberDiff line numberDiff line change
@@ -554,6 +554,12 @@ def test_many_weakrefs(self):
554554
vals[x] = cls(str(x))
555555
del vals
556556

557+
def test_constructor(self):
558+
T = TypeVar(name="T")
559+
self.assertEqual(T.__name__, "T")
560+
self.assertEqual(T.__constraints__, ())
561+
self.assertIs(T.__bound__, None)
562+
557563

558564
def template_replace(templates: list[str], replacements: dict[str, list[str]]) -> list[tuple[str]]:
559565
"""Renders templates with possible combinations of replacements.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix crash when :class:`typing.TypeVar` is constructed with a keyword
2+
argument. Patch by Jelle Zijlstra.

Objects/typevarobject.c

+20-18
Original file line numberDiff line numberDiff line change
@@ -364,24 +364,26 @@ typevar_new_impl(PyTypeObject *type, PyObject *name, PyObject *constraints,
364364
}
365365
}
366366

367-
if (!PyTuple_CheckExact(constraints)) {
368-
PyErr_SetString(PyExc_TypeError,
369-
"constraints must be a tuple");
370-
return NULL;
371-
}
372-
Py_ssize_t n_constraints = PyTuple_GET_SIZE(constraints);
373-
if (n_constraints == 1) {
374-
PyErr_SetString(PyExc_TypeError,
375-
"A single constraint is not allowed");
376-
Py_XDECREF(bound);
377-
return NULL;
378-
} else if (n_constraints == 0) {
379-
constraints = NULL;
380-
} else if (bound != NULL) {
381-
PyErr_SetString(PyExc_TypeError,
382-
"Constraints cannot be combined with bound=...");
383-
Py_XDECREF(bound);
384-
return NULL;
367+
if (constraints != NULL) {
368+
if (!PyTuple_CheckExact(constraints)) {
369+
PyErr_SetString(PyExc_TypeError,
370+
"constraints must be a tuple");
371+
return NULL;
372+
}
373+
Py_ssize_t n_constraints = PyTuple_GET_SIZE(constraints);
374+
if (n_constraints == 1) {
375+
PyErr_SetString(PyExc_TypeError,
376+
"A single constraint is not allowed");
377+
Py_XDECREF(bound);
378+
return NULL;
379+
} else if (n_constraints == 0) {
380+
constraints = NULL;
381+
} else if (bound != NULL) {
382+
PyErr_SetString(PyExc_TypeError,
383+
"Constraints cannot be combined with bound=...");
384+
Py_XDECREF(bound);
385+
return NULL;
386+
}
385387
}
386388
PyObject *module = caller();
387389
if (module == NULL) {

0 commit comments

Comments
 (0)