Skip to content

[3.7] bpo-38191: Accept arbitrary keyword names in NamedTuple(). (GH-16222) #16239

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 1 commit into from
Sep 17, 2019
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 @@ -2536,6 +2536,34 @@ def test_namedtuple_keyword_usage(self):
with self.assertRaises(TypeError):
NamedTuple('Name', x=1, y='a')

def test_namedtuple_special_keyword_names(self):
NT = NamedTuple("NT", cls=type, self=object, typename=str, fields=list)
self.assertEqual(NT.__name__, 'NT')
self.assertEqual(NT._fields, ('cls', 'self', 'typename', 'fields'))
a = NT(cls=str, self=42, typename='foo', fields=[('bar', tuple)])
self.assertEqual(a.cls, str)
self.assertEqual(a.self, 42)
self.assertEqual(a.typename, 'foo')
self.assertEqual(a.fields, [('bar', tuple)])

def test_namedtuple_errors(self):
with self.assertRaises(TypeError):
NamedTuple.__new__()
with self.assertRaises(TypeError):
NamedTuple()
with self.assertRaises(TypeError):
NamedTuple('Emp', [('name', str)], None)
with self.assertRaises(ValueError):
NamedTuple('Emp', [('_name', str)])

Emp = NamedTuple(typename='Emp', name=str, id=int)
self.assertEqual(Emp.__name__, 'Emp')
self.assertEqual(Emp._fields, ('name', 'id'))

Emp = NamedTuple('Emp', fields=[('name', str), ('id', int)])
self.assertEqual(Emp.__name__, 'Emp')
self.assertEqual(Emp._fields, ('name', 'id'))

def test_pickle(self):
global Emp # pickle wants to reference the class by name
Emp = NamedTuple('Emp', [('name', str), ('id', int)])
Expand Down
25 changes: 24 additions & 1 deletion Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1405,13 +1405,36 @@ class Employee(NamedTuple):
"""
_root = True

def __new__(self, typename, fields=None, **kwargs):
def __new__(*args, **kwargs):
if not args:
raise TypeError('NamedTuple.__new__(): not enough arguments')
cls, *args = args # allow the "cls" keyword be passed
if args:
typename, *args = args # allow the "typename" keyword be passed
elif 'typename' in kwargs:
typename = kwargs.pop('typename')
else:
raise TypeError("NamedTuple.__new__() missing 1 required positional "
"argument: 'typename'")
if args:
try:
fields, = args # allow the "fields" keyword be passed
except ValueError:
raise TypeError(f'NamedTuple.__new__() takes from 2 to 3 '
f'positional arguments but {len(args) + 2} '
f'were given') from None
elif 'fields' in kwargs and len(kwargs) == 1:
fields = kwargs.pop('fields')
else:
fields = None

if fields is None:
fields = kwargs.items()
elif kwargs:
raise TypeError("Either list of fields or keywords"
" can be provided to NamedTuple, not both")
return _make_nmtuple(typename, fields)
__new__.__text_signature__ = '($cls, typename, fields=None, /, **kwargs)'


def NewType(name, tp):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Constructor of :class:`~typing.NamedTuple` type now accepts arbitrary keyword
argument names, including "cls", "self", "typename" and "fields".