blob: be4d4fdc6f83d155ac8de7a73207b7194c88cf43 [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 Hettingerbc288e82007-12-13 23:52:59 +00005from itertools import izip as _izip
Raymond Hettingerabfd8df2007-10-16 21:28:32 +00006from keyword import iskeyword as _iskeyword
Raymond Hettingerc37e5e02007-03-01 06:16:43 +00007import sys as _sys
8
Guido van Rossum64c06e32007-11-22 00:55:51 +00009# For bootstrapping reasons, the collection ABCs are defined in _abcoll.py.
10# They should however be considered an integral part of collections.py.
11from _abcoll import *
12import _abcoll
13__all__ += _abcoll.__all__
14
Raymond Hettinger01a09572007-10-23 20:37:41 +000015def namedtuple(typename, field_names, verbose=False):
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000016 """Returns a new subclass of tuple with named fields.
17
Raymond Hettinger01a09572007-10-23 20:37:41 +000018 >>> Point = namedtuple('Point', 'x y')
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000019 >>> Point.__doc__ # docstring for the new class
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000020 'Point(x, y)'
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000021 >>> p = Point(11, y=22) # instantiate with positional args or keywords
22 >>> p[0] + p[1] # works just like the tuple (11, 22)
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000023 33
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000024 >>> x, y = p # unpacks just like a tuple
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000025 >>> x, y
26 (11, 22)
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000027 >>> p.x + p.y # fields also accessable by name
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000028 33
Raymond Hettinger42da8742007-12-14 02:49:47 +000029 >>> d = p._asdict() # convert to a dictionary
Raymond Hettingera7fc4b12007-10-05 02:47:07 +000030 >>> d['x']
31 11
32 >>> Point(**d) # convert from a dictionary
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000033 Point(x=11, y=22)
Raymond Hettinger42da8742007-12-14 02:49:47 +000034 >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Raymond Hettingerd36a60e2007-09-17 00:55:00 +000035 Point(x=100, y=22)
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000036
37 """
38
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000039 # Parse and validate the field names
40 if isinstance(field_names, basestring):
Raymond Hettinger0e1d6062007-10-08 10:11:51 +000041 field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000042 field_names = tuple(field_names)
Raymond Hettinger050afbf2007-10-16 19:18:30 +000043 for name in (typename,) + field_names:
Raymond Hettinger2e1af252007-12-05 18:11:08 +000044 if not all(c.isalnum() or c=='_' for c in name):
Raymond Hettinger050afbf2007-10-16 19:18:30 +000045 raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
Raymond Hettingerabfd8df2007-10-16 21:28:32 +000046 if _iskeyword(name):
47 raise ValueError('Type names and field names cannot be a keyword: %r' % name)
Raymond Hettinger050afbf2007-10-16 19:18:30 +000048 if name[0].isdigit():
49 raise ValueError('Type names and field names cannot start with a number: %r' % name)
Raymond Hettinger163f6222007-10-09 01:36:23 +000050 seen_names = set()
51 for name in field_names:
Raymond Hettinger42da8742007-12-14 02:49:47 +000052 if name.startswith('_'):
53 raise ValueError('Field names cannot start with an underscore: %r' % name)
Raymond Hettinger163f6222007-10-09 01:36:23 +000054 if name in seen_names:
Raymond Hettinger050afbf2007-10-16 19:18:30 +000055 raise ValueError('Encountered duplicate field name: %r' % name)
Raymond Hettinger163f6222007-10-09 01:36:23 +000056 seen_names.add(name)
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000057
58 # Create and fill-in the class template
Raymond Hettinger2b03d452007-09-18 03:33:19 +000059 argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000060 reprtxt = ', '.join('%s=%%r' % name for name in field_names)
61 template = '''class %(typename)s(tuple):
Raymond Hettinger48eca672007-12-14 18:08:20 +000062 '%(typename)s(%(argtxt)s)' \n
63 __slots__ = () \n
64 _fields = property(lambda self: %(field_names)r) \n
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000065 def __new__(cls, %(argtxt)s):
Raymond Hettinger48eca672007-12-14 18:08:20 +000066 return tuple.__new__(cls, (%(argtxt)s)) \n
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000067 def __repr__(self):
Raymond Hettinger48eca672007-12-14 18:08:20 +000068 return '%(typename)s(%(reprtxt)s)' %% self \n
Raymond Hettinger42da8742007-12-14 02:49:47 +000069 def _asdict(self, dict=dict, zip=zip):
Raymond Hettinger48eca672007-12-14 18:08:20 +000070 'Return a new dict which maps field names to their values'
71 return dict(zip(%(field_names)r, self)) \n
Raymond Hettinger42da8742007-12-14 02:49:47 +000072 def _replace(self, **kwds):
Raymond Hettingereeeb9c42007-11-15 02:44:53 +000073 'Return a new %(typename)s object replacing specified fields with new values'
Raymond Hettinger07ae83f2007-12-14 19:19:59 +000074 return %(typename)s(*map(kwds.get, %(field_names)r, self)) \n\n''' % locals()
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000075 for i, name in enumerate(field_names):
Raymond Hettinger2b03d452007-09-18 03:33:19 +000076 template += ' %s = property(itemgetter(%d))\n' % (name, i)
77 if verbose:
78 print template
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000079
80 # Execute the template string in a temporary namespace
Raymond Hettingerbc288e82007-12-13 23:52:59 +000081 namespace = dict(itemgetter=_itemgetter, zip=_izip)
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000082 try:
Raymond Hettinger0e1d6062007-10-08 10:11:51 +000083 exec template in namespace
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000084 except SyntaxError, e:
85 raise SyntaxError(e.message + ':\n' + template)
Raymond Hettinger0e1d6062007-10-08 10:11:51 +000086 result = namespace[typename]
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000087
88 # For pickling to work, the __module__ variable needs to be set to the frame
89 # where the named tuple is created. Bypass this step in enviroments where
90 # sys._getframe is not defined (Jython for example).
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000091 if hasattr(_sys, '_getframe'):
92 result.__module__ = _sys._getframe(1).f_globals['__name__']
Raymond Hettinger2115bbc2007-10-08 09:14:28 +000093
Raymond Hettinger5a41daf2007-05-19 01:11:16 +000094 return result
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
Raymond Hettingerc37e5e02007-03-01 06:16:43 +000099
100
101if __name__ == '__main__':
Raymond Hettingerd36a60e2007-09-17 00:55:00 +0000102 # verify that instances can be pickled
Raymond Hettingerc37e5e02007-03-01 06:16:43 +0000103 from cPickle import loads, dumps
Raymond Hettinger01a09572007-10-23 20:37:41 +0000104 Point = namedtuple('Point', 'x, y', True)
Raymond Hettingerc37e5e02007-03-01 06:16:43 +0000105 p = Point(x=10, y=20)
106 assert p == loads(dumps(p))
107
Raymond Hettingereeeb9c42007-11-15 02:44:53 +0000108 # test and demonstrate ability to override methods
109 Point.__repr__ = lambda self: 'Point(%.3f, %.3f)' % self
110 print p
111
Raymond Hettingerc37e5e02007-03-01 06:16:43 +0000112 import doctest
Raymond Hettinger01a09572007-10-23 20:37:41 +0000113 TestResults = namedtuple('TestResults', 'failed attempted')
Raymond Hettingerc37e5e02007-03-01 06:16:43 +0000114 print TestResults(*doctest.testmod())