blob: c2b1176fe51a7bb00ea03caa8f5927b655a530d4 [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
7def NamedTuple(typename, s):
8 """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 Hettingerd36a60e2007-09-17 00:55:00 +000021 >>> p # readable __repr__ with name=value style
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000022 Point(x=11, y=22)
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000023 >>> p.__replace__('x', 100) # __replace__() is like str.replace() but targets a named field
24 Point(x=100, y=22)
25 >>> d = dict(zip(p.__fields__, p)) # use __fields__ to make a dictionary
26 >>> d['x']
27 11
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000028
29 """
30
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000031 field_names = tuple(s.replace(',', ' ').split()) # names separated by spaces and/or commas
32 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 Hettinger5a41daf2007-05-19 01:11:16 +000034 argtxt = ', '.join(field_names)
35 reprtxt = ', '.join('%s=%%r' % name for name in field_names)
36 template = '''class %(typename)s(tuple):
37 '%(typename)s(%(argtxt)s)'
38 __slots__ = ()
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000039 __fields__ = %(field_names)r
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000040 def __new__(cls, %(argtxt)s):
41 return tuple.__new__(cls, (%(argtxt)s,))
42 def __repr__(self):
43 return '%(typename)s(%(reprtxt)s)' %% self
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000044 def __replace__(self, field, value):
45 'Return a new %(typename)s object replacing one field with a new value'
46 return %(typename)s(**dict(zip(%(field_names)r, self) + [(field, value)]))
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000047 ''' % locals()
48 for i, name in enumerate(field_names):
Raymond Hettingerf3241a32007-05-19 01:50:11 +000049 template += '\n %s = property(itemgetter(%d))\n' % (name, i)
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000050 m = dict(itemgetter=_itemgetter)
51 exec template in m
52 result = m[typename]
53 if hasattr(_sys, '_getframe'):
54 result.__module__ = _sys._getframe(1).f_globals['__name__']
55 return result
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000056
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000057
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000058
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000059
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000060
61
62if __name__ == '__main__':
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000063 # verify that instances can be pickled
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000064 from cPickle import loads, dumps
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000065 Point = NamedTuple('Point', 'x, y')
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000066 p = Point(x=10, y=20)
67 assert p == loads(dumps(p))
68
69 import doctest
70 TestResults = NamedTuple('TestResults', 'failed attempted')
71 print TestResults(*doctest.testmod())