blob: 7b107123171c7637017cdbd05c3f3a6b61328595 [file] [log] [blame]
Raymond Hettingerc37e5e02007-03-01 06:16:43 +00001__all__ = ['deque', 'defaultdict', 'NamedTuple']
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 Hettinger2b03d452007-09-18 03:33:19 +00007def NamedTuple(typename, s, verbose=False):
Raymond Hettingerc37e5e02007-03-01 06:16:43 +00008 """Returns a new subclass of tuple with named fields.
9
10 >>> Point = NamedTuple('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 Hettinger2b03d452007-09-18 03:33:19 +000031 field_names = tuple(s.replace(',', ' ').split()) # names separated by spaces and/or commas
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000032 if not ''.join((typename,) + field_names).replace('_', '').isalnum():
Raymond Hettinger0d6a8cc2007-05-21 08:13:35 +000033 raise ValueError('Type names and field names can only contain alphanumeric characters and underscores')
Raymond Hettingera7fc4b12007-10-05 02:47:07 +000034 if any(name.startswith('__') and name.endswith('__') for name in field_names):
35 raise ValueError('Field names cannot start and end with double underscores')
Raymond Hettinger2b03d452007-09-18 03:33:19 +000036 argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000037 reprtxt = ', '.join('%s=%%r' % name for name in field_names)
38 template = '''class %(typename)s(tuple):
39 '%(typename)s(%(argtxt)s)'
40 __slots__ = ()
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000041 __fields__ = %(field_names)r
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000042 def __new__(cls, %(argtxt)s):
Raymond Hettinger2b03d452007-09-18 03:33:19 +000043 return tuple.__new__(cls, (%(argtxt)s))
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000044 def __repr__(self):
45 return '%(typename)s(%(reprtxt)s)' %% self
Raymond Hettingera7fc4b12007-10-05 02:47:07 +000046 def __asdict__(self, dict=dict, zip=zip):
47 'Return a new dict mapping field names to their values'
48 return dict(zip(%(field_names)r, self))
49 def __replace__(self, field, value, dict=dict, zip=zip):
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000050 'Return a new %(typename)s object replacing one field with a new value'
Raymond Hettinger2b03d452007-09-18 03:33:19 +000051 return %(typename)s(**dict(zip(%(field_names)r, self) + [(field, value)])) \n''' % locals()
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000052 for i, name in enumerate(field_names):
Raymond Hettinger2b03d452007-09-18 03:33:19 +000053 template += ' %s = property(itemgetter(%d))\n' % (name, i)
54 if verbose:
55 print template
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000056 m = dict(itemgetter=_itemgetter)
57 exec template in m
58 result = m[typename]
59 if hasattr(_sys, '_getframe'):
60 result.__module__ = _sys._getframe(1).f_globals['__name__']
61 return result
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000062
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000063
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000064
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000065
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000066
67
68if __name__ == '__main__':
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000069 # verify that instances can be pickled
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000070 from cPickle import loads, dumps
Raymond Hettinger2b03d452007-09-18 03:33:19 +000071 Point = NamedTuple('Point', 'x, y', True)
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000072 p = Point(x=10, y=20)
73 assert p == loads(dumps(p))
74
75 import doctest
76 TestResults = NamedTuple('TestResults', 'failed attempted')
77 print TestResults(*doctest.testmod())