1 from operator import itemgetter as _itemgetter
2 from keyword import iskeyword as _iskeyword
5 def namedtuple(typename, field_names, verbose=False, rename=False):
6 """Returns a new subclass of tuple with named fields.
8 >>> Point = namedtuple('Point', 'x y')
9 >>> Point.__doc__ # docstring for the new class
11 >>> p = Point(11, y=22) # instantiate with positional args or keywords
12 >>> p[0] + p[1] # indexable like a plain tuple
14 >>> x, y = p # unpack like a regular tuple
17 >>> p.x + p.y # fields also accessable by name
19 >>> d = p._asdict() # convert to a dictionary
22 >>> Point(**d) # convert from a dictionary
24 >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
29 # Parse and validate the field names. Validation serves two purposes,
30 # generating informative error messages and preventing template injection attacks.
31 if isinstance(field_names, basestring):
32 field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
33 field_names = tuple(map(str, field_names))
35 names = list(field_names)
37 for i, name in enumerate(names):
38 if (not min(c.isalnum() or c=='_' for c in name) or _iskeyword(name)
39 or not name or name[0].isdigit() or name.startswith('_')
43 field_names = tuple(names)
44 for name in (typename,) + field_names:
45 if not min(c.isalnum() or c=='_' for c in name):
46 raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
48 raise ValueError('Type names and field names cannot be a keyword: %r' % name)
50 raise ValueError('Type names and field names cannot start with a number: %r' % name)
52 for name in field_names:
53 if name.startswith('_') and not rename:
54 raise ValueError('Field names cannot start with an underscore: %r' % name)
55 if name in seen_names:
56 raise ValueError('Encountered duplicate field name: %r' % name)
59 # Create and fill-in the class template
60 numfields = len(field_names)
61 argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes
62 reprtxt = ', '.join('%s=%%r' % name for name in field_names)
63 template = '''class %(typename)s(tuple):
64 '%(typename)s(%(argtxt)s)' \n
66 _fields = %(field_names)r \n
67 def __new__(_cls, %(argtxt)s):
68 return _tuple.__new__(_cls, (%(argtxt)s)) \n
70 def _make(cls, iterable, new=tuple.__new__, len=len):
71 'Make a new %(typename)s object from a sequence or iterable'
72 result = new(cls, iterable)
73 if len(result) != %(numfields)d:
74 raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
77 return '%(typename)s(%(reprtxt)s)' %% self \n
79 'Return a new dict which maps field names to their values'
80 return dict(zip(self._fields, self)) \n
81 def _replace(_self, **kwds):
82 'Return a new %(typename)s object replacing specified fields with new values'
83 result = _self._make(map(kwds.pop, %(field_names)r, _self))
85 raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
87 def __getnewargs__(self):
88 return tuple(self) \n\n''' % locals()
89 for i, name in enumerate(field_names):
90 template += ' %s = _property(_itemgetter(%d))\n' % (name, i)
94 # Execute the template string in a temporary namespace
95 namespace = dict(_itemgetter=_itemgetter, __name__='namedtuple_%s' % typename,
96 _property=property, _tuple=tuple)
98 exec template in namespace
99 except SyntaxError, e:
100 raise SyntaxError(e.message + ':\n' + template)
101 result = namespace[typename]
103 # For pickling to work, the __module__ variable needs to be set to the frame
104 # where the named tuple is created. Bypass this step in enviroments where
105 # sys._getframe is not defined (Jython for example) or sys._getframe is not
106 # defined for arguments greater than 0 (IronPython).
108 result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__')
109 except (AttributeError, ValueError):