Skip to content

gh-98852: Fix subscription of type aliases #98920

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -3916,6 +3916,34 @@ class A:
# C version of GenericAlias
self.assertEqual(list[A()].__parameters__, (T,))

def test_non_generic_subscript(self):
T = TypeVar('T')
class G(Generic[T]):
pass
class A:
__parameters__ = (T,)

for s in (int, G, A, List, list,
TypeVar, TypeVarTuple, ParamSpec,
types.GenericAlias, types.UnionType):

for t in Tuple, tuple:
with self.subTest(tuple=t, sub=s):
self.assertEqual(t[s, T][int], t[s, int])
self.assertEqual(t[T, s][int], t[int, s])
a = t[s]
with self.assertRaises(TypeError):
a[int]

for c in Callable, collections.abc.Callable:
with self.subTest(callable=c, sub=s):
self.assertEqual(c[[s], T][int], c[[s], int])
self.assertEqual(c[[T], s][int], c[[int], s])
a = c[[s], s]
with self.assertRaises(TypeError):
a[int]


class ClassVarTests(BaseTestCase):

def test_basics(self):
Expand Down
4 changes: 4 additions & 0 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1437,6 +1437,10 @@ def _determine_new_args(self, args):
new_args = []
for old_arg in self.__args__:

if isinstance(old_arg, type):
new_args.append(old_arg)
continue

substfunc = getattr(old_arg, '__typing_subst__', None)
if substfunc:
new_arg = substfunc(new_arg_by_param[old_arg])
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Fix subscription of type aliases containing bare generic types or types like
:class:`~typing.TypeVar`: for example ``tuple[A, T][int]`` and
``tuple[TypeVar, T][int]``, where ``A`` is a generic type, and ``T`` is a
type variable.
7 changes: 7 additions & 0 deletions Objects/genericaliasobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,13 @@ _Py_subs_parameters(PyObject *self, PyObject *args, PyObject *parameters, PyObje
}
for (Py_ssize_t iarg = 0, jarg = 0; iarg < nargs; iarg++) {
PyObject *arg = PyTuple_GET_ITEM(args, iarg);
if (PyType_Check(arg)) {
Py_INCREF(arg);
PyTuple_SET_ITEM(newargs, jarg, arg);
jarg++;
continue;
}

int unpack = _is_unpacked_typevartuple(arg);
if (unpack < 0) {
Py_DECREF(newargs);
Expand Down