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