Skip to content

Commit

Permalink
[3.12] gh-124498: Fix TypeAliasType not to be generic, when `type_p…
Browse files Browse the repository at this point in the history
…arams=()` (GH-124499) (#124604)

gh-124498: Fix `TypeAliasType` not to be generic, when `type_params=()` (GH-124499)
(cherry picked from commit abe5f79)

Co-authored-by: sobolevn <[email protected]>
  • Loading branch information
miss-islington and sobolevn authored Sep 26, 2024
1 parent 42432e5 commit 4659026
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
13 changes: 13 additions & 0 deletions Lib/test/test_type_aliases.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,19 @@ def test_generic(self):
self.assertEqual(TA.__value__, list[T])
self.assertEqual(TA.__type_params__, (T,))
self.assertEqual(TA.__module__, __name__)
self.assertIs(type(TA[int]), types.GenericAlias)

def test_not_generic(self):
TA = TypeAliasType("TA", list[int], type_params=())
self.assertEqual(TA.__name__, "TA")
self.assertEqual(TA.__value__, list[int])
self.assertEqual(TA.__type_params__, ())
self.assertEqual(TA.__module__, __name__)
with self.assertRaisesRegex(
TypeError,
"Only generic type aliases are subscriptable",
):
TA[int]

def test_keywords(self):
TA = TypeAliasType(name="TA", value=int)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix :class:`typing.TypeAliasType` not to be generic, when ``type_params`` is
an empty tuple.
11 changes: 10 additions & 1 deletion Objects/typevarobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -1364,7 +1364,16 @@ typealias_alloc(PyObject *name, PyObject *type_params, PyObject *compute_value,
return NULL;
}
ta->name = Py_NewRef(name);
ta->type_params = Py_IsNone(type_params) ? NULL : Py_XNewRef(type_params);
if (
type_params == NULL
|| Py_IsNone(type_params)
|| (PyTuple_Check(type_params) && PyTuple_GET_SIZE(type_params) == 0)
) {
ta->type_params = NULL;
}
else {
ta->type_params = Py_NewRef(type_params);
}
ta->compute_value = Py_XNewRef(compute_value);
ta->value = Py_XNewRef(value);
ta->module = Py_XNewRef(module);
Expand Down

0 comments on commit 4659026

Please sign in to comment.