Brett Cannon | 23a4a7b | 2008-05-12 00:56:28 +0000 | [diff] [blame] | 1 | __all__ = ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList', |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 2 | 'UserString', 'Counter', 'OrderedDict'] |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 3 | # For bootstrapping reasons, the collection ABCs are defined in _abcoll.py. |
| 4 | # They should however be considered an integral part of collections.py. |
| 5 | from _abcoll import * |
| 6 | import _abcoll |
| 7 | __all__ += _abcoll.__all__ |
| 8 | |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 9 | from _collections import deque, defaultdict |
| 10 | from operator import itemgetter as _itemgetter |
| 11 | from keyword import iskeyword as _iskeyword |
| 12 | import sys as _sys |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 13 | import heapq as _heapq |
Raymond Hettinger | ea9f8db | 2009-03-02 21:28:41 +0000 | [diff] [blame] | 14 | from itertools import repeat as _repeat, chain as _chain, starmap as _starmap |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 15 | |
| 16 | ################################################################################ |
| 17 | ### OrderedDict |
| 18 | ################################################################################ |
| 19 | |
| 20 | class OrderedDict(dict, MutableMapping): |
| 21 | |
| 22 | def __init__(self, *args, **kwds): |
| 23 | if len(args) > 1: |
| 24 | raise TypeError('expected at most 1 arguments, got %d' % len(args)) |
Raymond Hettinger | 08c70cf | 2009-03-03 20:47:29 +0000 | [diff] [blame^] | 25 | try: |
| 26 | self.__keys |
| 27 | except AttributeError: |
| 28 | # Note the underlying data structure for this class is likely to |
| 29 | # change in the future. Do not rely on it or access it directly. |
| 30 | self.__keys = [] |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 31 | self.update(*args, **kwds) |
| 32 | |
| 33 | def clear(self): |
Raymond Hettinger | 08c70cf | 2009-03-03 20:47:29 +0000 | [diff] [blame^] | 34 | del self.__keys[:] |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 35 | dict.clear(self) |
| 36 | |
| 37 | def __setitem__(self, key, value): |
| 38 | if key not in self: |
Raymond Hettinger | 08c70cf | 2009-03-03 20:47:29 +0000 | [diff] [blame^] | 39 | self.__keys.append(key) |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 40 | dict.__setitem__(self, key, value) |
| 41 | |
| 42 | def __delitem__(self, key): |
| 43 | dict.__delitem__(self, key) |
Raymond Hettinger | 08c70cf | 2009-03-03 20:47:29 +0000 | [diff] [blame^] | 44 | self.__keys.remove(key) |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 45 | |
| 46 | def __iter__(self): |
Raymond Hettinger | 08c70cf | 2009-03-03 20:47:29 +0000 | [diff] [blame^] | 47 | return iter(self.__keys) |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 48 | |
| 49 | def __reversed__(self): |
Raymond Hettinger | 08c70cf | 2009-03-03 20:47:29 +0000 | [diff] [blame^] | 50 | return reversed(self.__keys) |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 51 | |
| 52 | def popitem(self): |
| 53 | if not self: |
| 54 | raise KeyError('dictionary is empty') |
Raymond Hettinger | 08c70cf | 2009-03-03 20:47:29 +0000 | [diff] [blame^] | 55 | key = self.__keys.pop() |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 56 | value = dict.pop(self, key) |
| 57 | return key, value |
| 58 | |
| 59 | def __reduce__(self): |
| 60 | items = [[k, self[k]] for k in self] |
| 61 | inst_dict = vars(self).copy() |
Raymond Hettinger | 08c70cf | 2009-03-03 20:47:29 +0000 | [diff] [blame^] | 62 | inst_dict.pop('__keys', None) |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 63 | return (self.__class__, (items,), inst_dict) |
| 64 | |
| 65 | setdefault = MutableMapping.setdefault |
| 66 | update = MutableMapping.update |
| 67 | pop = MutableMapping.pop |
| 68 | keys = MutableMapping.keys |
| 69 | values = MutableMapping.values |
| 70 | items = MutableMapping.items |
| 71 | |
| 72 | def __repr__(self): |
| 73 | if not self: |
| 74 | return '%s()' % (self.__class__.__name__,) |
| 75 | return '%s(%r)' % (self.__class__.__name__, list(self.items())) |
| 76 | |
| 77 | def copy(self): |
| 78 | return self.__class__(self) |
| 79 | |
| 80 | @classmethod |
| 81 | def fromkeys(cls, iterable, value=None): |
| 82 | d = cls() |
| 83 | for key in iterable: |
| 84 | d[key] = value |
| 85 | return d |
| 86 | |
| 87 | def __eq__(self, other): |
| 88 | if isinstance(other, OrderedDict): |
Raymond Hettinger | ea9f8db | 2009-03-02 21:28:41 +0000 | [diff] [blame] | 89 | return len(self)==len(other) and all(p==q for p, q in zip(self.items(), other.items())) |
Raymond Hettinger | 2d32f63 | 2009-03-02 21:24:57 +0000 | [diff] [blame] | 90 | return dict.__eq__(self, other) |
| 91 | |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 92 | |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 93 | |
Raymond Hettinger | 48b8b66 | 2008-02-05 01:53:00 +0000 | [diff] [blame] | 94 | ################################################################################ |
| 95 | ### namedtuple |
| 96 | ################################################################################ |
| 97 | |
Benjamin Peterson | a86f2c0 | 2009-02-10 02:41:10 +0000 | [diff] [blame] | 98 | def namedtuple(typename, field_names, verbose=False, rename=False): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 99 | """Returns a new subclass of tuple with named fields. |
| 100 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 101 | >>> Point = namedtuple('Point', 'x y') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 102 | >>> Point.__doc__ # docstring for the new class |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 103 | 'Point(x, y)' |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 104 | >>> p = Point(11, y=22) # instantiate with positional args or keywords |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 105 | >>> p[0] + p[1] # indexable like a plain tuple |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 106 | 33 |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 107 | >>> x, y = p # unpack like a regular tuple |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 108 | >>> x, y |
| 109 | (11, 22) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 110 | >>> p.x + p.y # fields also accessable by name |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 111 | 33 |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 112 | >>> d = p._asdict() # convert to a dictionary |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 113 | >>> d['x'] |
| 114 | 11 |
| 115 | >>> Point(**d) # convert from a dictionary |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 116 | Point(x=11, y=22) |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 117 | >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 118 | Point(x=100, y=22) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 119 | |
| 120 | """ |
| 121 | |
Christian Heimes | 2380ac7 | 2008-01-09 00:17:24 +0000 | [diff] [blame] | 122 | # Parse and validate the field names. Validation serves two purposes, |
| 123 | # generating informative error messages and preventing template injection attacks. |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 124 | if isinstance(field_names, str): |
| 125 | field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas |
Benjamin Peterson | e9bbc8b | 2008-09-28 02:06:32 +0000 | [diff] [blame] | 126 | field_names = tuple(map(str, field_names)) |
Benjamin Peterson | a86f2c0 | 2009-02-10 02:41:10 +0000 | [diff] [blame] | 127 | if rename: |
| 128 | names = list(field_names) |
| 129 | seen = set() |
| 130 | for i, name in enumerate(names): |
| 131 | if (not all(c.isalnum() or c=='_' for c in name) or _iskeyword(name) |
| 132 | or not name or name[0].isdigit() or name.startswith('_') |
| 133 | or name in seen): |
| 134 | names[i] = '_%d' % (i+1) |
| 135 | seen.add(name) |
| 136 | field_names = tuple(names) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 137 | for name in (typename,) + field_names: |
Christian Heimes | b9eccbf | 2007-12-05 20:18:38 +0000 | [diff] [blame] | 138 | if not all(c.isalnum() or c=='_' for c in name): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 139 | raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name) |
| 140 | if _iskeyword(name): |
| 141 | raise ValueError('Type names and field names cannot be a keyword: %r' % name) |
| 142 | if name[0].isdigit(): |
| 143 | raise ValueError('Type names and field names cannot start with a number: %r' % name) |
| 144 | seen_names = set() |
| 145 | for name in field_names: |
Benjamin Peterson | a86f2c0 | 2009-02-10 02:41:10 +0000 | [diff] [blame] | 146 | if name.startswith('_') and not rename: |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 147 | raise ValueError('Field names cannot start with an underscore: %r' % name) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 148 | if name in seen_names: |
| 149 | raise ValueError('Encountered duplicate field name: %r' % name) |
| 150 | seen_names.add(name) |
| 151 | |
| 152 | # Create and fill-in the class template |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 153 | numfields = len(field_names) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 154 | argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes |
Guido van Rossum | d59da4b | 2007-05-22 18:11:13 +0000 | [diff] [blame] | 155 | reprtxt = ', '.join('%s=%%r' % name for name in field_names) |
| 156 | template = '''class %(typename)s(tuple): |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 157 | '%(typename)s(%(argtxt)s)' \n |
| 158 | __slots__ = () \n |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 159 | _fields = %(field_names)r \n |
Guido van Rossum | d59da4b | 2007-05-22 18:11:13 +0000 | [diff] [blame] | 160 | def __new__(cls, %(argtxt)s): |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 161 | return tuple.__new__(cls, (%(argtxt)s)) \n |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 162 | @classmethod |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 163 | def _make(cls, iterable, new=tuple.__new__, len=len): |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 164 | 'Make a new %(typename)s object from a sequence or iterable' |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 165 | result = new(cls, iterable) |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 166 | if len(result) != %(numfields)d: |
| 167 | raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result)) |
| 168 | return result \n |
Guido van Rossum | d59da4b | 2007-05-22 18:11:13 +0000 | [diff] [blame] | 169 | def __repr__(self): |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 170 | return '%(typename)s(%(reprtxt)s)' %% self \n |
Raymond Hettinger | a4f52b1 | 2009-03-02 22:28:31 +0000 | [diff] [blame] | 171 | def _asdict(self): |
| 172 | 'Return a new OrderedDict which maps field names to their values' |
| 173 | return OrderedDict(zip(self._fields, self)) \n |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 174 | def _replace(self, **kwds): |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 175 | 'Return a new %(typename)s object replacing specified fields with new values' |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 176 | result = self._make(map(kwds.pop, %(field_names)r, self)) |
| 177 | if kwds: |
| 178 | raise ValueError('Got unexpected field names: %%r' %% kwds.keys()) |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 179 | return result \n |
| 180 | def __getnewargs__(self): |
| 181 | return tuple(self) \n\n''' % locals() |
Guido van Rossum | d59da4b | 2007-05-22 18:11:13 +0000 | [diff] [blame] | 182 | for i, name in enumerate(field_names): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 183 | template += ' %s = property(itemgetter(%d))\n' % (name, i) |
| 184 | if verbose: |
| 185 | print(template) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 186 | |
Georg Brandl | f08a9dd | 2008-06-10 16:57:31 +0000 | [diff] [blame] | 187 | # Execute the template string in a temporary namespace and |
| 188 | # support tracing utilities by setting a value for frame.f_globals['__name__'] |
Raymond Hettinger | a4f52b1 | 2009-03-02 22:28:31 +0000 | [diff] [blame] | 189 | namespace = dict(itemgetter=_itemgetter, __name__='namedtuple_%s' % typename, |
| 190 | OrderedDict=OrderedDict) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 191 | try: |
| 192 | exec(template, namespace) |
| 193 | except SyntaxError as e: |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 194 | raise SyntaxError(e.msg + ':\n' + template) from e |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 195 | result = namespace[typename] |
| 196 | |
| 197 | # For pickling to work, the __module__ variable needs to be set to the frame |
| 198 | # where the named tuple is created. Bypass this step in enviroments where |
| 199 | # sys._getframe is not defined (Jython for example). |
Guido van Rossum | d59da4b | 2007-05-22 18:11:13 +0000 | [diff] [blame] | 200 | if hasattr(_sys, '_getframe'): |
Raymond Hettinger | 0f05517 | 2009-01-27 10:06:09 +0000 | [diff] [blame] | 201 | result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__') |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 202 | |
Guido van Rossum | d59da4b | 2007-05-22 18:11:13 +0000 | [diff] [blame] | 203 | return result |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 204 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 205 | |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 206 | ######################################################################## |
| 207 | ### Counter |
| 208 | ######################################################################## |
| 209 | |
| 210 | class Counter(dict): |
| 211 | '''Dict subclass for counting hashable items. Sometimes called a bag |
| 212 | or multiset. Elements are stored as dictionary keys and their counts |
| 213 | are stored as dictionary values. |
| 214 | |
| 215 | >>> c = Counter('abracadabra') # count elements from a string |
| 216 | |
| 217 | >>> c.most_common(3) # three most common elements |
| 218 | [('a', 5), ('r', 2), ('b', 2)] |
| 219 | >>> sorted(c) # list all unique elements |
| 220 | ['a', 'b', 'c', 'd', 'r'] |
| 221 | >>> ''.join(sorted(c.elements())) # list elements with repetitions |
| 222 | 'aaaaabbcdrr' |
| 223 | >>> sum(c.values()) # total of all counts |
| 224 | 11 |
| 225 | |
| 226 | >>> c['a'] # count of letter 'a' |
| 227 | 5 |
| 228 | >>> for elem in 'shazam': # update counts from an iterable |
| 229 | ... c[elem] += 1 # by adding 1 to each element's count |
| 230 | >>> c['a'] # now there are seven 'a' |
| 231 | 7 |
| 232 | >>> del c['r'] # remove all 'r' |
| 233 | >>> c['r'] # now there are zero 'r' |
| 234 | 0 |
| 235 | |
| 236 | >>> d = Counter('simsalabim') # make another counter |
| 237 | >>> c.update(d) # add in the second counter |
| 238 | >>> c['a'] # now there are nine 'a' |
| 239 | 9 |
| 240 | |
| 241 | >>> c.clear() # empty the counter |
| 242 | >>> c |
| 243 | Counter() |
| 244 | |
| 245 | Note: If a count is set to zero or reduced to zero, it will remain |
| 246 | in the counter until the entry is deleted or the counter is cleared: |
| 247 | |
| 248 | >>> c = Counter('aaabbc') |
| 249 | >>> c['b'] -= 2 # reduce the count of 'b' by two |
| 250 | >>> c.most_common() # 'b' is still in, but its count is zero |
| 251 | [('a', 3), ('c', 1), ('b', 0)] |
| 252 | |
| 253 | ''' |
| 254 | # References: |
| 255 | # http://en.wikipedia.org/wiki/Multiset |
| 256 | # http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html |
| 257 | # http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm |
| 258 | # http://code.activestate.com/recipes/259174/ |
| 259 | # Knuth, TAOCP Vol. II section 4.6.3 |
| 260 | |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 261 | def __init__(self, iterable=None, **kwds): |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 262 | '''Create a new, empty Counter object. And if given, count elements |
| 263 | from an input iterable. Or, initialize the count from another mapping |
| 264 | of elements to their counts. |
| 265 | |
| 266 | >>> c = Counter() # a new, empty counter |
| 267 | >>> c = Counter('gallahad') # a new counter from an iterable |
| 268 | >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 269 | >>> c = Counter(a=4, b=2) # a new counter from keyword args |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 270 | |
| 271 | ''' |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 272 | self.update(iterable, **kwds) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 273 | |
| 274 | def __missing__(self, key): |
| 275 | 'The count of elements not in the Counter is zero.' |
| 276 | # Needed so that self[missing_item] does not raise KeyError |
| 277 | return 0 |
| 278 | |
| 279 | def most_common(self, n=None): |
| 280 | '''List the n most common elements and their counts from the most |
| 281 | common to the least. If n is None, then list all element counts. |
| 282 | |
| 283 | >>> Counter('abracadabra').most_common(3) |
| 284 | [('a', 5), ('r', 2), ('b', 2)] |
| 285 | |
| 286 | ''' |
| 287 | # Emulate Bag.sortedByCount from Smalltalk |
| 288 | if n is None: |
| 289 | return sorted(self.items(), key=_itemgetter(1), reverse=True) |
| 290 | return _heapq.nlargest(n, self.items(), key=_itemgetter(1)) |
| 291 | |
| 292 | def elements(self): |
| 293 | '''Iterator over elements repeating each as many times as its count. |
| 294 | |
| 295 | >>> c = Counter('ABCABC') |
| 296 | >>> sorted(c.elements()) |
| 297 | ['A', 'A', 'B', 'B', 'C', 'C'] |
| 298 | |
| 299 | # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1 |
| 300 | >>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) |
| 301 | >>> product = 1 |
| 302 | >>> for factor in prime_factors.elements(): # loop over factors |
| 303 | ... product *= factor # and multiply them |
| 304 | >>> product |
| 305 | 1836 |
| 306 | |
| 307 | Note, if an element's count has been set to zero or is a negative |
| 308 | number, elements() will ignore it. |
| 309 | |
| 310 | ''' |
| 311 | # Emulate Bag.do from Smalltalk and Multiset.begin from C++. |
| 312 | return _chain.from_iterable(_starmap(_repeat, self.items())) |
| 313 | |
| 314 | # Override dict methods where necessary |
| 315 | |
| 316 | @classmethod |
| 317 | def fromkeys(cls, iterable, v=None): |
| 318 | # There is no equivalent method for counters because setting v=1 |
| 319 | # means that no element can have a count greater than one. |
| 320 | raise NotImplementedError( |
| 321 | 'Counter.fromkeys() is undefined. Use Counter(iterable) instead.') |
| 322 | |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 323 | def update(self, iterable=None, **kwds): |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 324 | '''Like dict.update() but add counts instead of replacing them. |
| 325 | |
| 326 | Source can be an iterable, a dictionary, or another Counter instance. |
| 327 | |
| 328 | >>> c = Counter('which') |
| 329 | >>> c.update('witch') # add elements from another iterable |
| 330 | >>> d = Counter('watch') |
| 331 | >>> c.update(d) # add elements from another counter |
| 332 | >>> c['h'] # four 'h' in which, witch, and watch |
| 333 | 4 |
| 334 | |
| 335 | ''' |
| 336 | # The regular dict.update() operation makes no sense here because the |
| 337 | # replace behavior results in the some of original untouched counts |
| 338 | # being mixed-in with all of the other counts for a mismash that |
| 339 | # doesn't have a straight-forward interpretation in most counting |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 340 | # contexts. Instead, we implement straight-addition. Both the inputs |
| 341 | # and outputs are allowed to contain zero and negative counts. |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 342 | |
| 343 | if iterable is not None: |
| 344 | if isinstance(iterable, Mapping): |
Raymond Hettinger | dd01f8f | 2009-01-22 09:09:55 +0000 | [diff] [blame] | 345 | if self: |
| 346 | for elem, count in iterable.items(): |
| 347 | self[elem] += count |
| 348 | else: |
| 349 | dict.update(self, iterable) # fast path when counter is empty |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 350 | else: |
| 351 | for elem in iterable: |
| 352 | self[elem] += 1 |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 353 | if kwds: |
| 354 | self.update(kwds) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 355 | |
| 356 | def copy(self): |
| 357 | 'Like dict.copy() but returns a Counter instance instead of a dict.' |
| 358 | return Counter(self) |
| 359 | |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 360 | def __delitem__(self, elem): |
| 361 | 'Like dict.__delitem__() but does not raise KeyError for missing values.' |
| 362 | if elem in self: |
| 363 | dict.__delitem__(self, elem) |
| 364 | |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 365 | def __repr__(self): |
| 366 | if not self: |
| 367 | return '%s()' % self.__class__.__name__ |
| 368 | items = ', '.join(map('%r: %r'.__mod__, self.most_common())) |
| 369 | return '%s({%s})' % (self.__class__.__name__, items) |
| 370 | |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 371 | # Multiset-style mathematical operations discussed in: |
| 372 | # Knuth TAOCP Volume II section 4.6.3 exercise 19 |
| 373 | # and at http://en.wikipedia.org/wiki/Multiset |
| 374 | # |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 375 | # Outputs guaranteed to only include positive counts. |
| 376 | # |
| 377 | # To strip negative and zero counts, add-in an empty counter: |
| 378 | # c += Counter() |
| 379 | |
| 380 | def __add__(self, other): |
| 381 | '''Add counts from two counters. |
| 382 | |
| 383 | >>> Counter('abbb') + Counter('bcc') |
| 384 | Counter({'b': 4, 'c': 2, 'a': 1}) |
| 385 | |
| 386 | ''' |
| 387 | if not isinstance(other, Counter): |
| 388 | return NotImplemented |
| 389 | result = Counter() |
| 390 | for elem in set(self) | set(other): |
| 391 | newcount = self[elem] + other[elem] |
| 392 | if newcount > 0: |
| 393 | result[elem] = newcount |
| 394 | return result |
| 395 | |
| 396 | def __sub__(self, other): |
| 397 | ''' Subtract count, but keep only results with positive counts. |
| 398 | |
| 399 | >>> Counter('abbbc') - Counter('bccd') |
| 400 | Counter({'b': 2, 'a': 1}) |
| 401 | |
| 402 | ''' |
| 403 | if not isinstance(other, Counter): |
| 404 | return NotImplemented |
| 405 | result = Counter() |
Raymond Hettinger | e0d1b9f | 2009-01-21 20:36:27 +0000 | [diff] [blame] | 406 | for elem in set(self) | set(other): |
| 407 | newcount = self[elem] - other[elem] |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 408 | if newcount > 0: |
| 409 | result[elem] = newcount |
| 410 | return result |
| 411 | |
| 412 | def __or__(self, other): |
| 413 | '''Union is the maximum of value in either of the input counters. |
| 414 | |
| 415 | >>> Counter('abbb') | Counter('bcc') |
| 416 | Counter({'b': 3, 'c': 2, 'a': 1}) |
| 417 | |
| 418 | ''' |
| 419 | if not isinstance(other, Counter): |
| 420 | return NotImplemented |
| 421 | _max = max |
| 422 | result = Counter() |
| 423 | for elem in set(self) | set(other): |
| 424 | newcount = _max(self[elem], other[elem]) |
| 425 | if newcount > 0: |
| 426 | result[elem] = newcount |
| 427 | return result |
| 428 | |
| 429 | def __and__(self, other): |
| 430 | ''' Intersection is the minimum of corresponding counts. |
| 431 | |
| 432 | >>> Counter('abbb') & Counter('bcc') |
| 433 | Counter({'b': 1}) |
| 434 | |
| 435 | ''' |
| 436 | if not isinstance(other, Counter): |
| 437 | return NotImplemented |
| 438 | _min = min |
| 439 | result = Counter() |
| 440 | if len(self) < len(other): |
| 441 | self, other = other, self |
| 442 | for elem in filter(self.__contains__, other): |
| 443 | newcount = _min(self[elem], other[elem]) |
| 444 | if newcount > 0: |
| 445 | result[elem] = newcount |
| 446 | return result |
| 447 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 448 | |
Raymond Hettinger | 48b8b66 | 2008-02-05 01:53:00 +0000 | [diff] [blame] | 449 | ################################################################################ |
| 450 | ### UserDict |
| 451 | ################################################################################ |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 452 | |
Raymond Hettinger | 48b8b66 | 2008-02-05 01:53:00 +0000 | [diff] [blame] | 453 | class UserDict(MutableMapping): |
| 454 | |
| 455 | # Start by filling-out the abstract methods |
| 456 | def __init__(self, dict=None, **kwargs): |
| 457 | self.data = {} |
| 458 | if dict is not None: |
| 459 | self.update(dict) |
| 460 | if len(kwargs): |
| 461 | self.update(kwargs) |
| 462 | def __len__(self): return len(self.data) |
| 463 | def __getitem__(self, key): |
| 464 | if key in self.data: |
| 465 | return self.data[key] |
| 466 | if hasattr(self.__class__, "__missing__"): |
| 467 | return self.__class__.__missing__(self, key) |
| 468 | raise KeyError(key) |
| 469 | def __setitem__(self, key, item): self.data[key] = item |
| 470 | def __delitem__(self, key): del self.data[key] |
| 471 | def __iter__(self): |
| 472 | return iter(self.data) |
| 473 | |
Raymond Hettinger | 554c8b8 | 2008-02-05 22:54:43 +0000 | [diff] [blame] | 474 | # Modify __contains__ to work correctly when __missing__ is present |
| 475 | def __contains__(self, key): |
| 476 | return key in self.data |
Raymond Hettinger | 48b8b66 | 2008-02-05 01:53:00 +0000 | [diff] [blame] | 477 | |
| 478 | # Now, add the methods in dicts but not in MutableMapping |
| 479 | def __repr__(self): return repr(self.data) |
| 480 | def copy(self): |
| 481 | if self.__class__ is UserDict: |
| 482 | return UserDict(self.data.copy()) |
| 483 | import copy |
| 484 | data = self.data |
| 485 | try: |
| 486 | self.data = {} |
| 487 | c = copy.copy(self) |
| 488 | finally: |
| 489 | self.data = data |
| 490 | c.update(self) |
| 491 | return c |
| 492 | @classmethod |
| 493 | def fromkeys(cls, iterable, value=None): |
| 494 | d = cls() |
| 495 | for key in iterable: |
| 496 | d[key] = value |
| 497 | return d |
| 498 | |
Raymond Hettinger | 48b8b66 | 2008-02-05 01:53:00 +0000 | [diff] [blame] | 499 | |
| 500 | |
| 501 | ################################################################################ |
Raymond Hettinger | 53dbe39 | 2008-02-12 20:03:09 +0000 | [diff] [blame] | 502 | ### UserList |
| 503 | ################################################################################ |
| 504 | |
| 505 | class UserList(MutableSequence): |
| 506 | """A more or less complete user-defined wrapper around list objects.""" |
| 507 | def __init__(self, initlist=None): |
| 508 | self.data = [] |
| 509 | if initlist is not None: |
| 510 | # XXX should this accept an arbitrary sequence? |
| 511 | if type(initlist) == type(self.data): |
| 512 | self.data[:] = initlist |
| 513 | elif isinstance(initlist, UserList): |
| 514 | self.data[:] = initlist.data[:] |
| 515 | else: |
| 516 | self.data = list(initlist) |
| 517 | def __repr__(self): return repr(self.data) |
| 518 | def __lt__(self, other): return self.data < self.__cast(other) |
| 519 | def __le__(self, other): return self.data <= self.__cast(other) |
| 520 | def __eq__(self, other): return self.data == self.__cast(other) |
| 521 | def __ne__(self, other): return self.data != self.__cast(other) |
| 522 | def __gt__(self, other): return self.data > self.__cast(other) |
| 523 | def __ge__(self, other): return self.data >= self.__cast(other) |
| 524 | def __cast(self, other): |
| 525 | return other.data if isinstance(other, UserList) else other |
Raymond Hettinger | 53dbe39 | 2008-02-12 20:03:09 +0000 | [diff] [blame] | 526 | def __contains__(self, item): return item in self.data |
| 527 | def __len__(self): return len(self.data) |
| 528 | def __getitem__(self, i): return self.data[i] |
| 529 | def __setitem__(self, i, item): self.data[i] = item |
| 530 | def __delitem__(self, i): del self.data[i] |
| 531 | def __add__(self, other): |
| 532 | if isinstance(other, UserList): |
| 533 | return self.__class__(self.data + other.data) |
| 534 | elif isinstance(other, type(self.data)): |
| 535 | return self.__class__(self.data + other) |
| 536 | return self.__class__(self.data + list(other)) |
| 537 | def __radd__(self, other): |
| 538 | if isinstance(other, UserList): |
| 539 | return self.__class__(other.data + self.data) |
| 540 | elif isinstance(other, type(self.data)): |
| 541 | return self.__class__(other + self.data) |
| 542 | return self.__class__(list(other) + self.data) |
| 543 | def __iadd__(self, other): |
| 544 | if isinstance(other, UserList): |
| 545 | self.data += other.data |
| 546 | elif isinstance(other, type(self.data)): |
| 547 | self.data += other |
| 548 | else: |
| 549 | self.data += list(other) |
| 550 | return self |
| 551 | def __mul__(self, n): |
| 552 | return self.__class__(self.data*n) |
| 553 | __rmul__ = __mul__ |
| 554 | def __imul__(self, n): |
| 555 | self.data *= n |
| 556 | return self |
| 557 | def append(self, item): self.data.append(item) |
| 558 | def insert(self, i, item): self.data.insert(i, item) |
| 559 | def pop(self, i=-1): return self.data.pop(i) |
| 560 | def remove(self, item): self.data.remove(item) |
| 561 | def count(self, item): return self.data.count(item) |
| 562 | def index(self, item, *args): return self.data.index(item, *args) |
| 563 | def reverse(self): self.data.reverse() |
| 564 | def sort(self, *args, **kwds): self.data.sort(*args, **kwds) |
| 565 | def extend(self, other): |
| 566 | if isinstance(other, UserList): |
| 567 | self.data.extend(other.data) |
| 568 | else: |
| 569 | self.data.extend(other) |
| 570 | |
| 571 | |
| 572 | |
| 573 | ################################################################################ |
Raymond Hettinger | b3a65f8 | 2008-02-21 22:11:37 +0000 | [diff] [blame] | 574 | ### UserString |
| 575 | ################################################################################ |
| 576 | |
| 577 | class UserString(Sequence): |
| 578 | def __init__(self, seq): |
| 579 | if isinstance(seq, str): |
| 580 | self.data = seq |
| 581 | elif isinstance(seq, UserString): |
| 582 | self.data = seq.data[:] |
| 583 | else: |
| 584 | self.data = str(seq) |
| 585 | def __str__(self): return str(self.data) |
| 586 | def __repr__(self): return repr(self.data) |
| 587 | def __int__(self): return int(self.data) |
Raymond Hettinger | b3a65f8 | 2008-02-21 22:11:37 +0000 | [diff] [blame] | 588 | def __float__(self): return float(self.data) |
| 589 | def __complex__(self): return complex(self.data) |
| 590 | def __hash__(self): return hash(self.data) |
| 591 | |
| 592 | def __eq__(self, string): |
| 593 | if isinstance(string, UserString): |
| 594 | return self.data == string.data |
| 595 | return self.data == string |
| 596 | def __ne__(self, string): |
| 597 | if isinstance(string, UserString): |
| 598 | return self.data != string.data |
| 599 | return self.data != string |
| 600 | def __lt__(self, string): |
| 601 | if isinstance(string, UserString): |
| 602 | return self.data < string.data |
| 603 | return self.data < string |
| 604 | def __le__(self, string): |
| 605 | if isinstance(string, UserString): |
| 606 | return self.data <= string.data |
| 607 | return self.data <= string |
| 608 | def __gt__(self, string): |
| 609 | if isinstance(string, UserString): |
| 610 | return self.data > string.data |
| 611 | return self.data > string |
| 612 | def __ge__(self, string): |
| 613 | if isinstance(string, UserString): |
| 614 | return self.data >= string.data |
| 615 | return self.data >= string |
| 616 | |
| 617 | def __contains__(self, char): |
| 618 | if isinstance(char, UserString): |
| 619 | char = char.data |
| 620 | return char in self.data |
| 621 | |
| 622 | def __len__(self): return len(self.data) |
| 623 | def __getitem__(self, index): return self.__class__(self.data[index]) |
| 624 | def __add__(self, other): |
| 625 | if isinstance(other, UserString): |
| 626 | return self.__class__(self.data + other.data) |
| 627 | elif isinstance(other, str): |
| 628 | return self.__class__(self.data + other) |
| 629 | return self.__class__(self.data + str(other)) |
| 630 | def __radd__(self, other): |
| 631 | if isinstance(other, str): |
| 632 | return self.__class__(other + self.data) |
| 633 | return self.__class__(str(other) + self.data) |
| 634 | def __mul__(self, n): |
| 635 | return self.__class__(self.data*n) |
| 636 | __rmul__ = __mul__ |
| 637 | def __mod__(self, args): |
| 638 | return self.__class__(self.data % args) |
| 639 | |
| 640 | # the following methods are defined in alphabetical order: |
| 641 | def capitalize(self): return self.__class__(self.data.capitalize()) |
| 642 | def center(self, width, *args): |
| 643 | return self.__class__(self.data.center(width, *args)) |
| 644 | def count(self, sub, start=0, end=_sys.maxsize): |
| 645 | if isinstance(sub, UserString): |
| 646 | sub = sub.data |
| 647 | return self.data.count(sub, start, end) |
| 648 | def encode(self, encoding=None, errors=None): # XXX improve this? |
| 649 | if encoding: |
| 650 | if errors: |
| 651 | return self.__class__(self.data.encode(encoding, errors)) |
| 652 | return self.__class__(self.data.encode(encoding)) |
| 653 | return self.__class__(self.data.encode()) |
| 654 | def endswith(self, suffix, start=0, end=_sys.maxsize): |
| 655 | return self.data.endswith(suffix, start, end) |
| 656 | def expandtabs(self, tabsize=8): |
| 657 | return self.__class__(self.data.expandtabs(tabsize)) |
| 658 | def find(self, sub, start=0, end=_sys.maxsize): |
| 659 | if isinstance(sub, UserString): |
| 660 | sub = sub.data |
| 661 | return self.data.find(sub, start, end) |
| 662 | def format(self, *args, **kwds): |
| 663 | return self.data.format(*args, **kwds) |
| 664 | def index(self, sub, start=0, end=_sys.maxsize): |
| 665 | return self.data.index(sub, start, end) |
| 666 | def isalpha(self): return self.data.isalpha() |
| 667 | def isalnum(self): return self.data.isalnum() |
| 668 | def isdecimal(self): return self.data.isdecimal() |
| 669 | def isdigit(self): return self.data.isdigit() |
| 670 | def isidentifier(self): return self.data.isidentifier() |
| 671 | def islower(self): return self.data.islower() |
| 672 | def isnumeric(self): return self.data.isnumeric() |
| 673 | def isspace(self): return self.data.isspace() |
| 674 | def istitle(self): return self.data.istitle() |
| 675 | def isupper(self): return self.data.isupper() |
| 676 | def join(self, seq): return self.data.join(seq) |
| 677 | def ljust(self, width, *args): |
| 678 | return self.__class__(self.data.ljust(width, *args)) |
| 679 | def lower(self): return self.__class__(self.data.lower()) |
| 680 | def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars)) |
| 681 | def partition(self, sep): |
| 682 | return self.data.partition(sep) |
| 683 | def replace(self, old, new, maxsplit=-1): |
| 684 | if isinstance(old, UserString): |
| 685 | old = old.data |
| 686 | if isinstance(new, UserString): |
| 687 | new = new.data |
| 688 | return self.__class__(self.data.replace(old, new, maxsplit)) |
| 689 | def rfind(self, sub, start=0, end=_sys.maxsize): |
| 690 | return self.data.rfind(sub, start, end) |
| 691 | def rindex(self, sub, start=0, end=_sys.maxsize): |
| 692 | return self.data.rindex(sub, start, end) |
| 693 | def rjust(self, width, *args): |
| 694 | return self.__class__(self.data.rjust(width, *args)) |
| 695 | def rpartition(self, sep): |
| 696 | return self.data.rpartition(sep) |
| 697 | def rstrip(self, chars=None): |
| 698 | return self.__class__(self.data.rstrip(chars)) |
| 699 | def split(self, sep=None, maxsplit=-1): |
| 700 | return self.data.split(sep, maxsplit) |
| 701 | def rsplit(self, sep=None, maxsplit=-1): |
| 702 | return self.data.rsplit(sep, maxsplit) |
| 703 | def splitlines(self, keepends=0): return self.data.splitlines(keepends) |
| 704 | def startswith(self, prefix, start=0, end=_sys.maxsize): |
| 705 | return self.data.startswith(prefix, start, end) |
| 706 | def strip(self, chars=None): return self.__class__(self.data.strip(chars)) |
| 707 | def swapcase(self): return self.__class__(self.data.swapcase()) |
| 708 | def title(self): return self.__class__(self.data.title()) |
| 709 | def translate(self, *args): |
| 710 | return self.__class__(self.data.translate(*args)) |
| 711 | def upper(self): return self.__class__(self.data.upper()) |
| 712 | def zfill(self, width): return self.__class__(self.data.zfill(width)) |
| 713 | |
| 714 | |
| 715 | |
| 716 | ################################################################################ |
Raymond Hettinger | 48b8b66 | 2008-02-05 01:53:00 +0000 | [diff] [blame] | 717 | ### Simple tests |
| 718 | ################################################################################ |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 719 | |
| 720 | if __name__ == '__main__': |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 721 | # verify that instances can be pickled |
Guido van Rossum | 99603b0 | 2007-07-20 00:22:32 +0000 | [diff] [blame] | 722 | from pickle import loads, dumps |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 723 | Point = namedtuple('Point', 'x, y', True) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 724 | p = Point(x=10, y=20) |
| 725 | assert p == loads(dumps(p)) |
| 726 | |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 727 | # test and demonstrate ability to override methods |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 728 | class Point(namedtuple('Point', 'x y')): |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 729 | __slots__ = () |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 730 | @property |
| 731 | def hypot(self): |
| 732 | return (self.x ** 2 + self.y ** 2) ** 0.5 |
Christian Heimes | 790c823 | 2008-01-07 21:14:23 +0000 | [diff] [blame] | 733 | def __str__(self): |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 734 | return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot) |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 735 | |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 736 | for p in Point(3, 4), Point(14, 5/7.): |
Christian Heimes | 790c823 | 2008-01-07 21:14:23 +0000 | [diff] [blame] | 737 | print (p) |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 738 | |
| 739 | class Point(namedtuple('Point', 'x y')): |
| 740 | 'Point class with optimized _make() and _replace() without error-checking' |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 741 | __slots__ = () |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 742 | _make = classmethod(tuple.__new__) |
| 743 | def _replace(self, _map=map, **kwds): |
Christian Heimes | 2380ac7 | 2008-01-09 00:17:24 +0000 | [diff] [blame] | 744 | return self._make(_map(kwds.get, ('x', 'y'), self)) |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 745 | |
| 746 | print(Point(11, 22)._replace(x=100)) |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 747 | |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 748 | Point3D = namedtuple('Point3D', Point._fields + ('z',)) |
| 749 | print(Point3D.__doc__) |
| 750 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 751 | import doctest |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 752 | TestResults = namedtuple('TestResults', 'failed attempted') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 753 | print(TestResults(*doctest.testmod())) |