7
7
8
8
from _collections import deque , defaultdict
9
9
from operator import itemgetter as _itemgetter
10
- from itertools import izip as _izip
11
10
from keyword import iskeyword as _iskeyword
12
11
import sys as _sys
13
12
@@ -18,7 +17,7 @@ def namedtuple(typename, field_names, verbose=False):
18
17
>>> Point.__doc__ # docstring for the new class
19
18
'Point(x, y)'
20
19
>>> 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
22
21
33
23
22
>>> x, y = p # unpack like a regular tuple
24
23
>>> x, y
@@ -57,16 +56,17 @@ def namedtuple(typename, field_names, verbose=False):
57
56
# Create and fill-in the class template
58
57
argtxt = repr (field_names ).replace ("'" , "" )[1 :- 1 ] # tuple repr without parens or quotes
59
58
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 ))
60
60
template = '''class %(typename)s(tuple):
61
61
'%(typename)s(%(argtxt)s)' \n
62
62
__slots__ = () \n
63
63
def __new__(cls, %(argtxt)s):
64
64
return tuple.__new__(cls, (%(argtxt)s)) \n
65
65
def __repr__(self):
66
66
return '%(typename)s(%(reprtxt)s)' %% self \n
67
- def _asdict(self, dict=dict, zip=zip ):
67
+ def _asdict(t ):
68
68
'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
70
70
def _replace(self, **kwds):
71
71
'Return a new %(typename)s object replacing specified fields with new values'
72
72
return %(typename)s(*map(kwds.get, %(field_names)r, self)) \n
@@ -79,7 +79,7 @@ def _fields(self):
79
79
print template
80
80
81
81
# Execute the template string in a temporary namespace
82
- namespace = dict (itemgetter = _itemgetter , zip = _izip )
82
+ namespace = dict (itemgetter = _itemgetter )
83
83
try :
84
84
exec template in namespace
85
85
except SyntaxError , e :
0 commit comments