Skip to content

Commit 8777bca

Browse files
committed
Simplify and speedup _asdict() for named tuples.
1 parent 0423698 commit 8777bca

File tree

2 files changed

+7
-7
lines changed

2 files changed

+7
-7
lines changed

Doc/library/collections.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -394,9 +394,9 @@ Example::
394394
def __repr__(self):
395395
return 'Point(x=%r, y=%r)' % self
396396

397-
def _asdict(self):
397+
def _asdict(t):
398398
'Return a new dict which maps field names to their values'
399-
return dict(zip(('x', 'y'), self))
399+
return {'x': t[0], 'y': t[1]}
400400

401401
def _replace(self, **kwds):
402402
'Return a new Point object replacing specified fields with new values'

Lib/collections.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77

88
from _collections import deque, defaultdict
99
from operator import itemgetter as _itemgetter
10-
from itertools import izip as _izip
1110
from keyword import iskeyword as _iskeyword
1211
import sys as _sys
1312

@@ -18,7 +17,7 @@ def namedtuple(typename, field_names, verbose=False):
1817
>>> Point.__doc__ # docstring for the new class
1918
'Point(x, y)'
2019
>>> p = Point(11, y=22) # instantiate with positional args or keywords
21-
>>> p[0] + p[1] # indexable like a plain tuple: (11, 22)
20+
>>> p[0] + p[1] # indexable like a plain tuple
2221
33
2322
>>> x, y = p # unpack like a regular tuple
2423
>>> x, y
@@ -57,16 +56,17 @@ def namedtuple(typename, field_names, verbose=False):
5756
# Create and fill-in the class template
5857
argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes
5958
reprtxt = ', '.join('%s=%%r' % name for name in field_names)
59+
dicttxt = ', '.join('%r: t[%d]' % (name, pos) for pos, name in enumerate(field_names))
6060
template = '''class %(typename)s(tuple):
6161
'%(typename)s(%(argtxt)s)' \n
6262
__slots__ = () \n
6363
def __new__(cls, %(argtxt)s):
6464
return tuple.__new__(cls, (%(argtxt)s)) \n
6565
def __repr__(self):
6666
return '%(typename)s(%(reprtxt)s)' %% self \n
67-
def _asdict(self, dict=dict, zip=zip):
67+
def _asdict(t):
6868
'Return a new dict which maps field names to their values'
69-
return dict(zip(%(field_names)r, self)) \n
69+
return {%(dicttxt)s} \n
7070
def _replace(self, **kwds):
7171
'Return a new %(typename)s object replacing specified fields with new values'
7272
return %(typename)s(*map(kwds.get, %(field_names)r, self)) \n
@@ -79,7 +79,7 @@ def _fields(self):
7979
print template
8080

8181
# Execute the template string in a temporary namespace
82-
namespace = dict(itemgetter=_itemgetter, zip=_izip)
82+
namespace = dict(itemgetter=_itemgetter)
8383
try:
8484
exec template in namespace
8585
except SyntaxError, e:

0 commit comments

Comments
 (0)