blob: 816f864c98fa1acdb642791f8352b41d6980a573 [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 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 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 Hettinger2b03d452007-09-18 03:33:19 +000034 argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000035 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):
Raymond Hettinger2b03d452007-09-18 03:33:19 +000041 return tuple.__new__(cls, (%(argtxt)s))
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000042 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'
Raymond Hettinger2b03d452007-09-18 03:33:19 +000046 return %(typename)s(**dict(zip(%(field_names)r, self) + [(field, value)])) \n''' % locals()
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000047 for i, name in enumerate(field_names):
Raymond Hettinger2b03d452007-09-18 03:33:19 +000048 template += ' %s = property(itemgetter(%d))\n' % (name, i)
49 if verbose:
50 print template
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000051 m = dict(itemgetter=_itemgetter)
52 exec template in m
53 result = m[typename]
54 if hasattr(_sys, '_getframe'):
55 result.__module__ = _sys._getframe(1).f_globals['__name__']
56 return result
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
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000061
62
63if __name__ == '__main__':
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000064 # verify that instances can be pickled
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000065 from cPickle import loads, dumps
Raymond Hettinger2b03d452007-09-18 03:33:19 +000066 Point = NamedTuple('Point', 'x, y', True)
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000067 p = Point(x=10, y=20)
68 assert p == loads(dumps(p))
69
70 import doctest
71 TestResults = NamedTuple('TestResults', 'failed attempted')
72 print TestResults(*doctest.testmod())