blob: 884c91f1e76ae3ba8f051f984c1e59d6cdcc6aaa [file] [log] [blame]
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001__all__ = ['deque', 'defaultdict', 'namedtuple']
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002# For bootstrapping reasons, the collection ABCs are defined in _abcoll.py.
3# They should however be considered an integral part of collections.py.
4from _abcoll import *
5import _abcoll
6__all__ += _abcoll.__all__
7
Christian Heimes99170a52007-12-19 02:07:34 +00008from _collections import deque, defaultdict
9from operator import itemgetter as _itemgetter
10from keyword import iskeyword as _iskeyword
11import sys as _sys
12
Guido van Rossum8ce8a782007-11-01 19:42:39 +000013def namedtuple(typename, field_names, verbose=False):
Guido van Rossumd8faa362007-04-27 19:54:29 +000014 """Returns a new subclass of tuple with named fields.
15
Guido van Rossum8ce8a782007-11-01 19:42:39 +000016 >>> Point = namedtuple('Point', 'x y')
Thomas Wouters1b7f8912007-09-19 03:06:30 +000017 >>> Point.__doc__ # docstring for the new class
Guido van Rossumd8faa362007-04-27 19:54:29 +000018 'Point(x, y)'
Thomas Wouters1b7f8912007-09-19 03:06:30 +000019 >>> p = Point(11, y=22) # instantiate with positional args or keywords
Christian Heimes99170a52007-12-19 02:07:34 +000020 >>> p[0] + p[1] # indexable like a plain tuple
Guido van Rossumd8faa362007-04-27 19:54:29 +000021 33
Christian Heimes99170a52007-12-19 02:07:34 +000022 >>> x, y = p # unpack like a regular tuple
Guido van Rossumd8faa362007-04-27 19:54:29 +000023 >>> x, y
24 (11, 22)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000025 >>> p.x + p.y # fields also accessable by name
Guido van Rossumd8faa362007-04-27 19:54:29 +000026 33
Christian Heimes0449f632007-12-15 01:27:15 +000027 >>> d = p._asdict() # convert to a dictionary
Guido van Rossum8ce8a782007-11-01 19:42:39 +000028 >>> d['x']
29 11
30 >>> Point(**d) # convert from a dictionary
Guido van Rossumd8faa362007-04-27 19:54:29 +000031 Point(x=11, y=22)
Christian Heimes0449f632007-12-15 01:27:15 +000032 >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Thomas Wouters1b7f8912007-09-19 03:06:30 +000033 Point(x=100, y=22)
Guido van Rossumd8faa362007-04-27 19:54:29 +000034
35 """
36
Guido van Rossum8ce8a782007-11-01 19:42:39 +000037 # Parse and validate the field names
38 if isinstance(field_names, str):
39 field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
40 field_names = tuple(field_names)
41 for name in (typename,) + field_names:
Christian Heimesb9eccbf2007-12-05 20:18:38 +000042 if not all(c.isalnum() or c=='_' for c in name):
Guido van Rossum8ce8a782007-11-01 19:42:39 +000043 raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
44 if _iskeyword(name):
45 raise ValueError('Type names and field names cannot be a keyword: %r' % name)
46 if name[0].isdigit():
47 raise ValueError('Type names and field names cannot start with a number: %r' % name)
48 seen_names = set()
49 for name in field_names:
Christian Heimes0449f632007-12-15 01:27:15 +000050 if name.startswith('_'):
51 raise ValueError('Field names cannot start with an underscore: %r' % name)
Guido van Rossum8ce8a782007-11-01 19:42:39 +000052 if name in seen_names:
53 raise ValueError('Encountered duplicate field name: %r' % name)
54 seen_names.add(name)
55
56 # Create and fill-in the class template
Christian Heimesfaf2f632008-01-06 16:59:19 +000057 numfields = len(field_names)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000058 argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes
Guido van Rossumd59da4b2007-05-22 18:11:13 +000059 reprtxt = ', '.join('%s=%%r' % name for name in field_names)
Christian Heimes99170a52007-12-19 02:07:34 +000060 dicttxt = ', '.join('%r: t[%d]' % (name, pos) for pos, name in enumerate(field_names))
Guido van Rossumd59da4b2007-05-22 18:11:13 +000061 template = '''class %(typename)s(tuple):
Christian Heimes0449f632007-12-15 01:27:15 +000062 '%(typename)s(%(argtxt)s)' \n
63 __slots__ = () \n
Christian Heimesfaf2f632008-01-06 16:59:19 +000064 _fields = %(field_names)r \n
Guido van Rossumd59da4b2007-05-22 18:11:13 +000065 def __new__(cls, %(argtxt)s):
Christian Heimes0449f632007-12-15 01:27:15 +000066 return tuple.__new__(cls, (%(argtxt)s)) \n
Christian Heimesfaf2f632008-01-06 16:59:19 +000067 @classmethod
Christian Heimes043d6f62008-01-07 17:19:16 +000068 def _make(cls, iterable, new=tuple.__new__, len=len):
Christian Heimesfaf2f632008-01-06 16:59:19 +000069 'Make a new %(typename)s object from a sequence or iterable'
Christian Heimes043d6f62008-01-07 17:19:16 +000070 result = new(cls, iterable)
Christian Heimesfaf2f632008-01-06 16:59:19 +000071 if len(result) != %(numfields)d:
72 raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
73 return result \n
Guido van Rossumd59da4b2007-05-22 18:11:13 +000074 def __repr__(self):
Christian Heimes0449f632007-12-15 01:27:15 +000075 return '%(typename)s(%(reprtxt)s)' %% self \n
Christian Heimes99170a52007-12-19 02:07:34 +000076 def _asdict(t):
Christian Heimes0449f632007-12-15 01:27:15 +000077 'Return a new dict which maps field names to their values'
Christian Heimes99170a52007-12-19 02:07:34 +000078 return {%(dicttxt)s} \n
Christian Heimes0449f632007-12-15 01:27:15 +000079 def _replace(self, **kwds):
Guido van Rossum3d392eb2007-11-16 00:35:22 +000080 'Return a new %(typename)s object replacing specified fields with new values'
Christian Heimesfaf2f632008-01-06 16:59:19 +000081 result = self._make(map(kwds.pop, %(field_names)r, self))
82 if kwds:
83 raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
84 return result \n\n''' % locals()
Guido van Rossumd59da4b2007-05-22 18:11:13 +000085 for i, name in enumerate(field_names):
Thomas Wouters1b7f8912007-09-19 03:06:30 +000086 template += ' %s = property(itemgetter(%d))\n' % (name, i)
87 if verbose:
88 print(template)
Guido van Rossum8ce8a782007-11-01 19:42:39 +000089
90 # Execute the template string in a temporary namespace
Christian Heimes99170a52007-12-19 02:07:34 +000091 namespace = dict(itemgetter=_itemgetter)
Guido van Rossum8ce8a782007-11-01 19:42:39 +000092 try:
93 exec(template, namespace)
94 except SyntaxError as e:
Christian Heimes99170a52007-12-19 02:07:34 +000095 raise SyntaxError(e.msg + ':\n' + template) from e
Guido van Rossum8ce8a782007-11-01 19:42:39 +000096 result = namespace[typename]
97
98 # For pickling to work, the __module__ variable needs to be set to the frame
99 # where the named tuple is created. Bypass this step in enviroments where
100 # sys._getframe is not defined (Jython for example).
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000101 if hasattr(_sys, '_getframe'):
102 result.__module__ = _sys._getframe(1).f_globals['__name__']
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000103
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000104 return result
Guido van Rossumd8faa362007-04-27 19:54:29 +0000105
Guido van Rossumd8faa362007-04-27 19:54:29 +0000106
Guido van Rossumd8faa362007-04-27 19:54:29 +0000107
Guido van Rossumd8faa362007-04-27 19:54:29 +0000108
109
110if __name__ == '__main__':
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000111 # verify that instances can be pickled
Guido van Rossum99603b02007-07-20 00:22:32 +0000112 from pickle import loads, dumps
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000113 Point = namedtuple('Point', 'x, y', True)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000114 p = Point(x=10, y=20)
115 assert p == loads(dumps(p))
116
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000117 # test and demonstrate ability to override methods
Christian Heimes043d6f62008-01-07 17:19:16 +0000118 class Point(namedtuple('Point', 'x y')):
119 @property
120 def hypot(self):
121 return (self.x ** 2 + self.y ** 2) ** 0.5
122 def __repr__(self):
123 return 'Point(x=%.3f, y=%.3f, hypot=%.3f)' % (self.x, self.y, self.hypot)
124
125 print(Point(3, 4),'\n', Point(2, 5), '\n', Point(9./7, 6))
126
127 class Point(namedtuple('Point', 'x y')):
128 'Point class with optimized _make() and _replace() without error-checking'
129 _make = classmethod(tuple.__new__)
130 def _replace(self, _map=map, **kwds):
131 return self._make(_map(kwds.pop, ('x', 'y'), self))
132
133 print(Point(11, 22)._replace(x=100))
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000134
Guido van Rossumd8faa362007-04-27 19:54:29 +0000135 import doctest
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000136 TestResults = namedtuple('TestResults', 'failed attempted')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000137 print(TestResults(*doctest.testmod()))