Simplify creation of the __new__ method in namedtuple() (GH-20361)

This commit is contained in:
Raymond Hettinger 2020-05-25 21:39:00 -07:00 committed by GitHub
parent a2bbedc8b1
commit 3cfe5b7b8f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 2 additions and 4 deletions

View File

@ -406,11 +406,9 @@ def namedtuple(typename, field_names, *, rename=False, defaults=None, module=Non
# Create all the named tuple methods to be added to the class namespace
s = f'def __new__(_cls, {arg_list}): return _tuple_new(_cls, ({arg_list}))'
s = f'lambda _cls, {arg_list}: _tuple_new(_cls, ({arg_list}))'
namespace = {'_tuple_new': tuple_new, '__name__': f'namedtuple_{typename}'}
# Note: exec() has the side-effect of interning the field names
exec(s, namespace)
__new__ = namespace['__new__']
__new__ = eval(s, namespace)
__new__.__doc__ = f'Create new instance of {typename}({arg_list})'
if defaults is not None:
__new__.__defaults__ = defaults