blob: f5c524b25a87c8d606b5d9a8038ff2af9c8964cc [file] [log] [blame]
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001__all__ = ['deque', 'defaultdict', 'namedtuple']
Guido van Rossumd8faa362007-04-27 19:54:29 +00002
3from _collections import deque, defaultdict
4from operator import itemgetter as _itemgetter
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005from keyword import iskeyword as _iskeyword
Guido van Rossumd8faa362007-04-27 19:54:29 +00006import sys as _sys
7
Guido van Rossumcd16bf62007-06-13 18:07:49 +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
Guido van Rossum8ce8a782007-11-01 19:42:39 +000014def namedtuple(typename, field_names, verbose=False):
Guido van Rossumd8faa362007-04-27 19:54:29 +000015 """Returns a new subclass of tuple with named fields.
16
Guido van Rossum8ce8a782007-11-01 19:42:39 +000017 >>> Point = namedtuple('Point', 'x y')
Thomas Wouters1b7f8912007-09-19 03:06:30 +000018 >>> Point.__doc__ # docstring for the new class
Guido van Rossumd8faa362007-04-27 19:54:29 +000019 'Point(x, y)'
Thomas Wouters1b7f8912007-09-19 03:06:30 +000020 >>> p = Point(11, y=22) # instantiate with positional args or keywords
21 >>> p[0] + p[1] # works just like the tuple (11, 22)
Guido van Rossumd8faa362007-04-27 19:54:29 +000022 33
Thomas Wouters1b7f8912007-09-19 03:06:30 +000023 >>> x, y = p # unpacks just like a tuple
Guido van Rossumd8faa362007-04-27 19:54:29 +000024 >>> x, y
25 (11, 22)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000026 >>> p.x + p.y # fields also accessable by name
Guido van Rossumd8faa362007-04-27 19:54:29 +000027 33
Guido van Rossum8ce8a782007-11-01 19:42:39 +000028 >>> d = p.__asdict__() # convert to a dictionary
29 >>> d['x']
30 11
31 >>> Point(**d) # convert from a dictionary
Guido van Rossumd8faa362007-04-27 19:54:29 +000032 Point(x=11, y=22)
Guido van Rossum3d392eb2007-11-16 00:35:22 +000033 >>> p.__replace__(x=100) # __replace__() is like str.replace() but targets named fields
Thomas Wouters1b7f8912007-09-19 03:06:30 +000034 Point(x=100, y=22)
Guido van Rossumd8faa362007-04-27 19:54:29 +000035
36 """
37
Guido van Rossum8ce8a782007-11-01 19:42:39 +000038 # Parse and validate the field names
39 if isinstance(field_names, str):
40 field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
41 field_names = tuple(field_names)
42 for name in (typename,) + field_names:
Christian Heimesb9eccbf2007-12-05 20:18:38 +000043 if not all(c.isalnum() or c=='_' for c in name):
Guido van Rossum8ce8a782007-11-01 19:42:39 +000044 raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
45 if _iskeyword(name):
46 raise ValueError('Type names and field names cannot be a keyword: %r' % name)
47 if name[0].isdigit():
48 raise ValueError('Type names and field names cannot start with a number: %r' % name)
49 seen_names = set()
50 for name in field_names:
Christian Heimesb9eccbf2007-12-05 20:18:38 +000051 if name.startswith('__') and name.endswith('__') and len(name) > 3:
Guido van Rossum8ce8a782007-11-01 19:42:39 +000052 raise ValueError('Field names cannot start and end with double underscores: %r' % name)
53 if name in seen_names:
54 raise ValueError('Encountered duplicate field name: %r' % name)
55 seen_names.add(name)
56
57 # Create and fill-in the class template
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)
60 template = '''class %(typename)s(tuple):
61 '%(typename)s(%(argtxt)s)'
62 __slots__ = ()
Guido van Rossum3d392eb2007-11-16 00:35:22 +000063 __fields__ = property(lambda self: %(field_names)r)
Guido van Rossumd59da4b2007-05-22 18:11:13 +000064 def __new__(cls, %(argtxt)s):
Thomas Wouters1b7f8912007-09-19 03:06:30 +000065 return tuple.__new__(cls, (%(argtxt)s))
Guido van Rossumd59da4b2007-05-22 18:11:13 +000066 def __repr__(self):
67 return '%(typename)s(%(reprtxt)s)' %% self
Guido van Rossum8ce8a782007-11-01 19:42:39 +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))
Guido van Rossum3d392eb2007-11-16 00:35:22 +000071 def __replace__(self, **kwds):
72 'Return a new %(typename)s object replacing specified fields with new values'
Guido van Rossum053b4f32007-11-16 00:48:13 +000073 return %(typename)s(**dict(list(zip(%(field_names)r, self)) + list(kwds.items()))) \n''' % locals()
Guido van Rossumd59da4b2007-05-22 18:11:13 +000074 for i, name in enumerate(field_names):
Thomas Wouters1b7f8912007-09-19 03:06:30 +000075 template += ' %s = property(itemgetter(%d))\n' % (name, i)
76 if verbose:
77 print(template)
Guido van Rossum8ce8a782007-11-01 19:42:39 +000078
79 # Execute the template string in a temporary namespace
80 namespace = dict(itemgetter=_itemgetter)
81 try:
82 exec(template, namespace)
83 except SyntaxError as e:
84 raise SyntaxError(e.message + ':\n' + template)
85 result = namespace[typename]
86
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).
Guido van Rossumd59da4b2007-05-22 18:11:13 +000090 if hasattr(_sys, '_getframe'):
91 result.__module__ = _sys._getframe(1).f_globals['__name__']
Guido van Rossum8ce8a782007-11-01 19:42:39 +000092
Guido van Rossumd59da4b2007-05-22 18:11:13 +000093 return result
Guido van Rossumd8faa362007-04-27 19:54:29 +000094
Guido van Rossumd8faa362007-04-27 19:54:29 +000095
Guido van Rossumd8faa362007-04-27 19:54:29 +000096
Guido van Rossumd8faa362007-04-27 19:54:29 +000097
98
99if __name__ == '__main__':
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000100 # verify that instances can be pickled
Guido van Rossum99603b02007-07-20 00:22:32 +0000101 from pickle import loads, dumps
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000102 Point = namedtuple('Point', 'x, y', True)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000103 p = Point(x=10, y=20)
104 assert p == loads(dumps(p))
105
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000106 # test and demonstrate ability to override methods
107 Point.__repr__ = lambda self: 'Point(%.3f, %.3f)' % self
Guido van Rossum053b4f32007-11-16 00:48:13 +0000108 print(p)
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000109
Guido van Rossumd8faa362007-04-27 19:54:29 +0000110 import doctest
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000111 TestResults = namedtuple('TestResults', 'failed attempted')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000112 print(TestResults(*doctest.testmod()))