From b676ebd8e5c89889e7e73885aff4296158fa6153 Mon Sep 17 00:00:00 2001 From: Serhiy Storchaka Date: Wed, 4 May 2022 16:07:08 +0300 Subject: [PATCH] gh-92107: Add tests that subscription works on arbitrary named tuple types --- Lib/test/test_collections.py | 12 ++++++++++++ Lib/test/test_typing.py | 14 ++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/Lib/test/test_collections.py b/Lib/test/test_collections.py index 3a16045c5aa1ae..fa1d0e014dee92 100644 --- a/Lib/test/test_collections.py +++ b/Lib/test/test_collections.py @@ -698,6 +698,18 @@ def test_match_args(self): Point = namedtuple('Point', 'x y') self.assertEqual(Point.__match_args__, ('x', 'y')) + def test_non_generic_subscript(self): + # For backward compatibility, subscription works + # on arbitrary named tuple types. + Group = collections.namedtuple('Group', 'key group') + A = Group[int, list[int]] + self.assertEqual(A.__origin__, Group) + self.assertEqual(A.__parameters__, ()) + self.assertEqual(A.__args__, (int, list[int])) + a = A(1, [2]) + self.assertIs(type(a), Group) + self.assertEqual(a, (1, [2])) + ################################################################################ ### Abstract Base Classes diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py index 55e18c08537df7..8399465f6052da 100644 --- a/Lib/test/test_typing.py +++ b/Lib/test/test_typing.py @@ -5736,6 +5736,20 @@ class Y(Generic[T], NamedTuple): with self.assertRaises(TypeError): G[int, str] + def test_non_generic_subscript(self): + # For backward compatibility, subscription works + # on arbitrary NamedTuple types. + class Group(NamedTuple): + key: T + group: list[T] + A = Group[int] + self.assertEqual(A.__origin__, Group) + self.assertEqual(A.__parameters__, ()) + self.assertEqual(A.__args__, (int,)) + a = A(1, [2]) + self.assertIs(type(a), Group) + self.assertEqual(a, (1, [2])) + def test_namedtuple_keyword_usage(self): LocalEmployee = NamedTuple("LocalEmployee", name=str, age=int) nick = LocalEmployee('Nick', 25)