blob: 242de60564dc7b83a88927eed1c353dbaa3de488 [file] [log] [blame]
Raymond Hettingera48a2992007-10-08 21:26:58 +00001__all__ = ['deque', 'defaultdict', 'named_tuple']
Raymond Hettingereb979882007-02-28 18:37:52 +00002
3from _collections import deque, defaultdict
Raymond Hettingerc37e5e02007-03-01 06:16:43 +00004from operator import itemgetter as _itemgetter
5import sys as _sys
6
Raymond Hettingera48a2992007-10-08 21:26:58 +00007def named_tuple(typename, field_names, verbose=False):
Raymond Hettingerc37e5e02007-03-01 06:16:43 +00008 """Returns a new subclass of tuple with named fields.
9
Raymond Hettingera48a2992007-10-08 21:26:58 +000010 >>> Point = named_tuple('Point', 'x y')
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000011 >>> Point.__doc__ # docstring for the new class
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000012 'Point(x, y)'
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000013 >>> p = Point(11, y=22) # instantiate with positional args or keywords
14 >>> p[0] + p[1] # works just like the tuple (11, 22)
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000015 33
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000016 >>> x, y = p # unpacks just like a tuple
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000017 >>> x, y
18 (11, 22)
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000019 >>> p.x + p.y # fields also accessable by name
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000020 33
Raymond Hettingera7fc4b12007-10-05 02:47:07 +000021 >>> d = p.__asdict__() # convert to a dictionary
22 >>> d['x']
23 11
24 >>> Point(**d) # convert from a dictionary
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000025 Point(x=11, y=22)
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000026 >>> p.__replace__('x', 100) # __replace__() is like str.replace() but targets a named field
27 Point(x=100, y=22)
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000028
29 """
30
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000031 # Parse and validate the field names
32 if isinstance(field_names, basestring):
Raymond Hettinger0e1d6062007-10-08 10:11:51 +000033 field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000034 field_names = tuple(field_names)
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000035 if not ''.join((typename,) + field_names).replace('_', '').isalnum():
Raymond Hettinger0d6a8cc2007-05-21 08:13:35 +000036 raise ValueError('Type names and field names can only contain alphanumeric characters and underscores')
Raymond Hettingera7fc4b12007-10-05 02:47:07 +000037 if any(name.startswith('__') and name.endswith('__') for name in field_names):
38 raise ValueError('Field names cannot start and end with double underscores')
Raymond Hettingera48a2992007-10-08 21:26:58 +000039 if any(name[:1].isdigit() for name in field_names):
40 raise ValueError('Field names cannot start with a number')
41 if len(field_names) != len(set(field_names)):
42 raise ValueError('Encountered duplicate field name')
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000043
44 # Create and fill-in the class template
Raymond Hettinger2b03d452007-09-18 03:33:19 +000045 argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000046 reprtxt = ', '.join('%s=%%r' % name for name in field_names)
47 template = '''class %(typename)s(tuple):
48 '%(typename)s(%(argtxt)s)'
49 __slots__ = ()
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000050 __fields__ = %(field_names)r
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000051 def __new__(cls, %(argtxt)s):
Raymond Hettinger2b03d452007-09-18 03:33:19 +000052 return tuple.__new__(cls, (%(argtxt)s))
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000053 def __repr__(self):
54 return '%(typename)s(%(reprtxt)s)' %% self
Raymond Hettingera7fc4b12007-10-05 02:47:07 +000055 def __asdict__(self, dict=dict, zip=zip):
56 'Return a new dict mapping field names to their values'
57 return dict(zip(%(field_names)r, self))
58 def __replace__(self, field, value, dict=dict, zip=zip):
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000059 'Return a new %(typename)s object replacing one field with a new value'
Raymond Hettinger2b03d452007-09-18 03:33:19 +000060 return %(typename)s(**dict(zip(%(field_names)r, self) + [(field, value)])) \n''' % locals()
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000061 for i, name in enumerate(field_names):
Raymond Hettinger2b03d452007-09-18 03:33:19 +000062 template += ' %s = property(itemgetter(%d))\n' % (name, i)
63 if verbose:
64 print template
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000065
66 # Execute the template string in a temporary namespace
Raymond Hettinger0e1d6062007-10-08 10:11:51 +000067 namespace = dict(itemgetter=_itemgetter)
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000068 try:
Raymond Hettinger0e1d6062007-10-08 10:11:51 +000069 exec template in namespace
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000070 except SyntaxError, e:
71 raise SyntaxError(e.message + ':\n' + template)
Raymond Hettinger0e1d6062007-10-08 10:11:51 +000072 result = namespace[typename]
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000073
74 # For pickling to work, the __module__ variable needs to be set to the frame
75 # where the named tuple is created. Bypass this step in enviroments where
76 # sys._getframe is not defined (Jython for example).
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000077 if hasattr(_sys, '_getframe'):
78 result.__module__ = _sys._getframe(1).f_globals['__name__']
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000079
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000080 return result
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000081
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000082
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000083
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000084
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000085
86
87if __name__ == '__main__':
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000088 # verify that instances can be pickled
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000089 from cPickle import loads, dumps
Raymond Hettingera48a2992007-10-08 21:26:58 +000090 Point = named_tuple('Point', 'x, y', True)
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000091 p = Point(x=10, y=20)
92 assert p == loads(dumps(p))
93
94 import doctest
Raymond Hettingera48a2992007-10-08 21:26:58 +000095 TestResults = named_tuple('TestResults', 'failed attempted')
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000096 print TestResults(*doctest.testmod())