Skip to content

Commit 17ab556

Browse files
authored
gh-144321: Fix named tuple bug when input is a non-sequence iterable (#144600)
1 parent 936d60d commit 17ab556

File tree

3 files changed

+13
-2
lines changed

3 files changed

+13
-2
lines changed

Lib/test/test_typing.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8532,6 +8532,15 @@ class ThisWontWorkEither(NamedTuple):
85328532
def name(self):
85338533
return __class__.__name__
85348534

8535+
def test_named_tuple_non_sequence_input(self):
8536+
field_names = ["x", "y"]
8537+
field_values = [int, int]
8538+
Point = NamedTuple("Point", zip(field_names, field_values))
8539+
p = Point(1, 2)
8540+
self.assertEqual(p.x, 1)
8541+
self.assertEqual(p.y, 2)
8542+
self.assertEqual(repr(p),"Point(x=1, y=2)")
8543+
85358544

85368545
class TypedDictTests(BaseTestCase):
85378546
def test_basics_functional_syntax(self):

Lib/typing.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3075,8 +3075,7 @@ class Employee(NamedTuple):
30753075
"""
30763076
types = {n: _type_check(t, f"field {n} annotation must be a type")
30773077
for n, t in fields}
3078-
field_names = [n for n, _ in fields]
3079-
nt = _make_nmtuple(typename, field_names, _make_eager_annotate(types), module=_caller())
3078+
nt = _make_nmtuple(typename, types, _make_eager_annotate(types), module=_caller())
30803079
nt.__orig_bases__ = (NamedTuple,)
30813080
return nt
30823081

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
The functional syntax for creating :class:`typing.NamedTuple`
2+
classes now supports passing any :term:`iterable` of fields and types.
3+
Previously, only sequences were supported.

0 commit comments

Comments
 (0)