blob: e551f20d8e1822f7e921e5892ffe0bb7a57cb1c5 [file] [log] [blame]
Raymond Hettinger01a09572007-10-23 20:37:41 +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
Raymond Hettingerabfd8df2007-10-16 21:28:32 +00005from keyword import iskeyword as _iskeyword
Raymond Hettingerc37e5e02007-03-01 06:16:43 +00006import sys as _sys
7
Guido van Rossum64c06e32007-11-22 00:55:51 +00008# For bootstrapping reasons, the collection ABCs are defined in _abcoll.py.
9# They should however be considered an integral part of collections.py.
10from _abcoll import *
11import _abcoll
12__all__ += _abcoll.__all__
13
Raymond Hettinger01a09572007-10-23 20:37:41 +000014def namedtuple(typename, field_names, verbose=False):
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000015 """Returns a new subclass of tuple with named fields.
16
Raymond Hettinger01a09572007-10-23 20:37:41 +000017 >>> Point = namedtuple('Point', 'x y')
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000018 >>> Point.__doc__ # docstring for the new class
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000019 'Point(x, y)'
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000020 >>> p = Point(11, y=22) # instantiate with positional args or keywords
21 >>> p[0] + p[1] # works just like the tuple (11, 22)
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000022 33
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000023 >>> x, y = p # unpacks just like a tuple
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000024 >>> x, y
25 (11, 22)
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000026 >>> p.x + p.y # fields also accessable by name
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000027 33
Raymond Hettingera7fc4b12007-10-05 02:47:07 +000028 >>> d = p.__asdict__() # convert to a dictionary
29 >>> d['x']
30 11
31 >>> Point(**d) # convert from a dictionary
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000032 Point(x=11, y=22)
Raymond Hettingereeeb9c42007-11-15 02:44:53 +000033 >>> p.__replace__(x=100) # __replace__() is like str.replace() but targets named fields
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000034 Point(x=100, y=22)
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000035
36 """
37
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000038 # Parse and validate the field names
39 if isinstance(field_names, basestring):
Raymond Hettinger0e1d6062007-10-08 10:11:51 +000040 field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000041 field_names = tuple(field_names)
Raymond Hettinger050afbf2007-10-16 19:18:30 +000042 for name in (typename,) + field_names:
Raymond Hettinger2e1af252007-12-05 18:11:08 +000043 if not all(c.isalnum() or c=='_' for c in name):
Raymond Hettinger050afbf2007-10-16 19:18:30 +000044 raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
Raymond Hettingerabfd8df2007-10-16 21:28:32 +000045 if _iskeyword(name):
46 raise ValueError('Type names and field names cannot be a keyword: %r' % name)
Raymond Hettinger050afbf2007-10-16 19:18:30 +000047 if name[0].isdigit():
48 raise ValueError('Type names and field names cannot start with a number: %r' % name)
Raymond Hettinger163f6222007-10-09 01:36:23 +000049 seen_names = set()
50 for name in field_names:
Raymond Hettinger2e1af252007-12-05 18:11:08 +000051 if name.startswith('__') and name.endswith('__') and len(name) > 3:
Raymond Hettinger050afbf2007-10-16 19:18:30 +000052 raise ValueError('Field names cannot start and end with double underscores: %r' % name)
Raymond Hettinger163f6222007-10-09 01:36:23 +000053 if name in seen_names:
Raymond Hettinger050afbf2007-10-16 19:18:30 +000054 raise ValueError('Encountered duplicate field name: %r' % name)
Raymond Hettinger163f6222007-10-09 01:36:23 +000055 seen_names.add(name)
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000056
57 # Create and fill-in the class template
Raymond Hettinger2b03d452007-09-18 03:33:19 +000058 argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000059 reprtxt = ', '.join('%s=%%r' % name for name in field_names)
60 template = '''class %(typename)s(tuple):
61 '%(typename)s(%(argtxt)s)'
62 __slots__ = ()
Raymond Hettinger78f27e02007-11-14 22:56:16 +000063 __fields__ = property(lambda self: %(field_names)r)
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000064 def __new__(cls, %(argtxt)s):
Raymond Hettinger2b03d452007-09-18 03:33:19 +000065 return tuple.__new__(cls, (%(argtxt)s))
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000066 def __repr__(self):
67 return '%(typename)s(%(reprtxt)s)' %% self
Raymond Hettingera7fc4b12007-10-05 02:47:07 +000068 def __asdict__(self, dict=dict, zip=zip):
69 'Return a new dict mapping field names to their values'
70 return dict(zip(%(field_names)r, self))
Raymond Hettingereeeb9c42007-11-15 02:44:53 +000071 def __replace__(self, **kwds):
72 'Return a new %(typename)s object replacing specified fields with new values'
Raymond Hettinger5681cbc2007-11-15 02:55:42 +000073 return %(typename)s(**dict(zip(%(field_names)r, self) + kwds.items())) \n''' % locals()
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000074 for i, name in enumerate(field_names):
Raymond Hettinger2b03d452007-09-18 03:33:19 +000075 template += ' %s = property(itemgetter(%d))\n' % (name, i)
76 if verbose:
77 print template
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000078
79 # Execute the template string in a temporary namespace
Raymond Hettinger0e1d6062007-10-08 10:11:51 +000080 namespace = dict(itemgetter=_itemgetter)
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000081 try:
Raymond Hettinger0e1d6062007-10-08 10:11:51 +000082 exec template in namespace
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000083 except SyntaxError, e:
84 raise SyntaxError(e.message + ':\n' + template)
Raymond Hettinger0e1d6062007-10-08 10:11:51 +000085 result = namespace[typename]
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000086
87 # For pickling to work, the __module__ variable needs to be set to the frame
88 # where the named tuple is created. Bypass this step in enviroments where
89 # sys._getframe is not defined (Jython for example).
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000090 if hasattr(_sys, '_getframe'):
91 result.__module__ = _sys._getframe(1).f_globals['__name__']
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000092
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000093 return result
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000094
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000095
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000096
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000097
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000098
99
100if __name__ == '__main__':
Raymond Hettingerd36a60e2007-09-17 00:55:00 +0000101 # verify that instances can be pickled
Raymond Hettingerc37e5e02007-03-01 06:16:43 +0000102 from cPickle import loads, dumps
Raymond Hettinger01a09572007-10-23 20:37:41 +0000103 Point = namedtuple('Point', 'x, y', True)
Raymond Hettingerc37e5e02007-03-01 06:16:43 +0000104 p = Point(x=10, y=20)
105 assert p == loads(dumps(p))
106
Raymond Hettingereeeb9c42007-11-15 02:44:53 +0000107 # test and demonstrate ability to override methods
108 Point.__repr__ = lambda self: 'Point(%.3f, %.3f)' % self
109 print p
110
Raymond Hettingerc37e5e02007-03-01 06:16:43 +0000111 import doctest
Raymond Hettinger01a09572007-10-23 20:37:41 +0000112 TestResults = namedtuple('TestResults', 'failed attempted')
Raymond Hettingerc37e5e02007-03-01 06:16:43 +0000113 print TestResults(*doctest.testmod())