blob: 1ed5e4a223e0d6e4d4fab6ef74e4309696a1bb24 [file] [log] [blame]
Brett Cannon23a4a7b2008-05-12 00:56:28 +00001__all__ = ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList',
Raymond Hettinger2d32f632009-03-02 21:24:57 +00002 'UserString', 'Counter', 'OrderedDict']
Guido van Rossumcd16bf62007-06-13 18:07:49 +00003# For bootstrapping reasons, the collection ABCs are defined in _abcoll.py.
4# They should however be considered an integral part of collections.py.
5from _abcoll import *
6import _abcoll
7__all__ += _abcoll.__all__
8
Christian Heimes99170a52007-12-19 02:07:34 +00009from _collections import deque, defaultdict
10from operator import itemgetter as _itemgetter
11from keyword import iskeyword as _iskeyword
12import sys as _sys
Raymond Hettingerb8baf632009-01-14 02:20:07 +000013import heapq as _heapq
Raymond Hettingerea9f8db2009-03-02 21:28:41 +000014from itertools import repeat as _repeat, chain as _chain, starmap as _starmap
Raymond Hettinger2d32f632009-03-02 21:24:57 +000015
16################################################################################
17### OrderedDict
18################################################################################
19
20class OrderedDict(dict, MutableMapping):
Raymond Hettinger18ed2cb2009-03-19 23:14:39 +000021 'Dictionary that remembers insertion order'
22 # The inherited dict maps keys to values.
23 # The internal self.__map dictionary maps keys to links in a doubly linked list.
24 # The doubly linked list starts and ends with a sentinel element.
25 # The sentinel element never gets deleted. It simplifies the algorithm.
Raymond Hettingerbfb54562009-03-19 23:23:15 +000026 # Setting a new item causes a new link to append to the doubly linked list.
Raymond Hettinger18ed2cb2009-03-19 23:14:39 +000027 # Deleting an item uses self.__map to find the link, which is then removed.
28 # Iteration follows the linked list in order.
29 # Reverse iteration follows the links backwards.
30 # The inherited dict provides __getitem__, __len__, __contains__, and get.
31 # The remaining methods are order-aware.
Raymond Hettingerbfb54562009-03-19 23:23:15 +000032 # Big-Oh running times for all methods are the same as for regular dictionaries.
Raymond Hettinger2d32f632009-03-02 21:24:57 +000033
34 def __init__(self, *args, **kwds):
35 if len(args) > 1:
36 raise TypeError('expected at most 1 arguments, got %d' % len(args))
Raymond Hettinger08c70cf2009-03-03 20:47:29 +000037 try:
Raymond Hettingerdc879f02009-03-19 20:30:56 +000038 self.__end
Raymond Hettinger08c70cf2009-03-03 20:47:29 +000039 except AttributeError:
Raymond Hettingerdc879f02009-03-19 20:30:56 +000040 self.clear()
Raymond Hettinger2d32f632009-03-02 21:24:57 +000041 self.update(*args, **kwds)
42
43 def clear(self):
Raymond Hettingerdc879f02009-03-19 20:30:56 +000044 self.__end = end = []
45 end += [None, end, end] # sentinel node for doubly linked list
46 self.__map = {} # key --> [key, prev, next]
Raymond Hettinger2d32f632009-03-02 21:24:57 +000047 dict.clear(self)
48
49 def __setitem__(self, key, value):
50 if key not in self:
Raymond Hettingerdc879f02009-03-19 20:30:56 +000051 end = self.__end
52 curr = end[1]
53 curr[2] = end[1] = self.__map[key] = [key, curr, end]
Raymond Hettinger2d32f632009-03-02 21:24:57 +000054 dict.__setitem__(self, key, value)
55
56 def __delitem__(self, key):
57 dict.__delitem__(self, key)
Raymond Hettingerdc879f02009-03-19 20:30:56 +000058 key, prev, next = self.__map.pop(key)
59 prev[2] = next
60 next[1] = prev
Raymond Hettinger2d32f632009-03-02 21:24:57 +000061
62 def __iter__(self):
Raymond Hettingerdc879f02009-03-19 20:30:56 +000063 end = self.__end
Raymond Hettinger18ed2cb2009-03-19 23:14:39 +000064 curr = end[2] # start at first link
Raymond Hettingerdc879f02009-03-19 20:30:56 +000065 while curr is not end:
Raymond Hettinger18ed2cb2009-03-19 23:14:39 +000066 yield curr[0] # yield KEY for each link
67 curr = curr[2] # goto next link
Raymond Hettinger2d32f632009-03-02 21:24:57 +000068
69 def __reversed__(self):
Raymond Hettingerdc879f02009-03-19 20:30:56 +000070 end = self.__end
Raymond Hettinger18ed2cb2009-03-19 23:14:39 +000071 curr = end[1] # start at last link
Raymond Hettingerdc879f02009-03-19 20:30:56 +000072 while curr is not end:
Raymond Hettinger18ed2cb2009-03-19 23:14:39 +000073 yield curr[0] # yield KEY for each link
74 curr = curr[1] # goto prev link
Raymond Hettinger2d32f632009-03-02 21:24:57 +000075
76 def __reduce__(self):
77 items = [[k, self[k]] for k in self]
Raymond Hettingerdc879f02009-03-19 20:30:56 +000078 tmp = self.__map, self.__end
79 del self.__map, self.__end
Raymond Hettinger2d32f632009-03-02 21:24:57 +000080 inst_dict = vars(self).copy()
Raymond Hettingerdc879f02009-03-19 20:30:56 +000081 self.__map, self.__end = tmp
Raymond Hettinger14b89ff2009-03-03 22:20:56 +000082 if inst_dict:
83 return (self.__class__, (items,), inst_dict)
84 return self.__class__, (items,)
Raymond Hettinger2d32f632009-03-02 21:24:57 +000085
86 setdefault = MutableMapping.setdefault
87 update = MutableMapping.update
88 pop = MutableMapping.pop
89 keys = MutableMapping.keys
90 values = MutableMapping.values
91 items = MutableMapping.items
92
Raymond Hettinger18ed2cb2009-03-19 23:14:39 +000093 def popitem(self, last=True):
94 if not self:
95 raise KeyError('dictionary is empty')
96 key = next(reversed(self)) if last else next(iter(self))
97 value = self.pop(key)
98 return key, value
99
Raymond Hettinger2d32f632009-03-02 21:24:57 +0000100 def __repr__(self):
101 if not self:
102 return '%s()' % (self.__class__.__name__,)
103 return '%s(%r)' % (self.__class__.__name__, list(self.items()))
104
105 def copy(self):
106 return self.__class__(self)
107
108 @classmethod
109 def fromkeys(cls, iterable, value=None):
110 d = cls()
111 for key in iterable:
112 d[key] = value
113 return d
114
115 def __eq__(self, other):
116 if isinstance(other, OrderedDict):
Raymond Hettingerea9f8db2009-03-02 21:28:41 +0000117 return len(self)==len(other) and all(p==q for p, q in zip(self.items(), other.items()))
Raymond Hettinger2d32f632009-03-02 21:24:57 +0000118 return dict.__eq__(self, other)
119
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000120
Christian Heimes99170a52007-12-19 02:07:34 +0000121
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000122################################################################################
123### namedtuple
124################################################################################
125
Benjamin Petersona86f2c02009-02-10 02:41:10 +0000126def namedtuple(typename, field_names, verbose=False, rename=False):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000127 """Returns a new subclass of tuple with named fields.
128
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000129 >>> Point = namedtuple('Point', 'x y')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000130 >>> Point.__doc__ # docstring for the new class
Guido van Rossumd8faa362007-04-27 19:54:29 +0000131 'Point(x, y)'
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000132 >>> p = Point(11, y=22) # instantiate with positional args or keywords
Christian Heimes99170a52007-12-19 02:07:34 +0000133 >>> p[0] + p[1] # indexable like a plain tuple
Guido van Rossumd8faa362007-04-27 19:54:29 +0000134 33
Christian Heimes99170a52007-12-19 02:07:34 +0000135 >>> x, y = p # unpack like a regular tuple
Guido van Rossumd8faa362007-04-27 19:54:29 +0000136 >>> x, y
137 (11, 22)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000138 >>> p.x + p.y # fields also accessable by name
Guido van Rossumd8faa362007-04-27 19:54:29 +0000139 33
Christian Heimes0449f632007-12-15 01:27:15 +0000140 >>> d = p._asdict() # convert to a dictionary
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000141 >>> d['x']
142 11
143 >>> Point(**d) # convert from a dictionary
Guido van Rossumd8faa362007-04-27 19:54:29 +0000144 Point(x=11, y=22)
Christian Heimes0449f632007-12-15 01:27:15 +0000145 >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000146 Point(x=100, y=22)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000147
148 """
149
Christian Heimes2380ac72008-01-09 00:17:24 +0000150 # Parse and validate the field names. Validation serves two purposes,
151 # generating informative error messages and preventing template injection attacks.
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000152 if isinstance(field_names, str):
153 field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +0000154 field_names = tuple(map(str, field_names))
Benjamin Petersona86f2c02009-02-10 02:41:10 +0000155 if rename:
156 names = list(field_names)
157 seen = set()
158 for i, name in enumerate(names):
159 if (not all(c.isalnum() or c=='_' for c in name) or _iskeyword(name)
160 or not name or name[0].isdigit() or name.startswith('_')
161 or name in seen):
162 names[i] = '_%d' % (i+1)
163 seen.add(name)
164 field_names = tuple(names)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000165 for name in (typename,) + field_names:
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000166 if not all(c.isalnum() or c=='_' for c in name):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000167 raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
168 if _iskeyword(name):
169 raise ValueError('Type names and field names cannot be a keyword: %r' % name)
170 if name[0].isdigit():
171 raise ValueError('Type names and field names cannot start with a number: %r' % name)
172 seen_names = set()
173 for name in field_names:
Benjamin Petersona86f2c02009-02-10 02:41:10 +0000174 if name.startswith('_') and not rename:
Christian Heimes0449f632007-12-15 01:27:15 +0000175 raise ValueError('Field names cannot start with an underscore: %r' % name)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000176 if name in seen_names:
177 raise ValueError('Encountered duplicate field name: %r' % name)
178 seen_names.add(name)
179
180 # Create and fill-in the class template
Christian Heimesfaf2f632008-01-06 16:59:19 +0000181 numfields = len(field_names)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000182 argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000183 reprtxt = ', '.join('%s=%%r' % name for name in field_names)
184 template = '''class %(typename)s(tuple):
Christian Heimes0449f632007-12-15 01:27:15 +0000185 '%(typename)s(%(argtxt)s)' \n
186 __slots__ = () \n
Christian Heimesfaf2f632008-01-06 16:59:19 +0000187 _fields = %(field_names)r \n
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000188 def __new__(cls, %(argtxt)s):
Christian Heimes0449f632007-12-15 01:27:15 +0000189 return tuple.__new__(cls, (%(argtxt)s)) \n
Christian Heimesfaf2f632008-01-06 16:59:19 +0000190 @classmethod
Christian Heimes043d6f62008-01-07 17:19:16 +0000191 def _make(cls, iterable, new=tuple.__new__, len=len):
Christian Heimesfaf2f632008-01-06 16:59:19 +0000192 'Make a new %(typename)s object from a sequence or iterable'
Christian Heimes043d6f62008-01-07 17:19:16 +0000193 result = new(cls, iterable)
Christian Heimesfaf2f632008-01-06 16:59:19 +0000194 if len(result) != %(numfields)d:
195 raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
196 return result \n
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000197 def __repr__(self):
Christian Heimes0449f632007-12-15 01:27:15 +0000198 return '%(typename)s(%(reprtxt)s)' %% self \n
Raymond Hettingera4f52b12009-03-02 22:28:31 +0000199 def _asdict(self):
200 'Return a new OrderedDict which maps field names to their values'
201 return OrderedDict(zip(self._fields, self)) \n
Christian Heimes0449f632007-12-15 01:27:15 +0000202 def _replace(self, **kwds):
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000203 'Return a new %(typename)s object replacing specified fields with new values'
Christian Heimesfaf2f632008-01-06 16:59:19 +0000204 result = self._make(map(kwds.pop, %(field_names)r, self))
205 if kwds:
206 raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000207 return result \n
208 def __getnewargs__(self):
209 return tuple(self) \n\n''' % locals()
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000210 for i, name in enumerate(field_names):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000211 template += ' %s = property(itemgetter(%d))\n' % (name, i)
212 if verbose:
213 print(template)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000214
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000215 # Execute the template string in a temporary namespace and
216 # support tracing utilities by setting a value for frame.f_globals['__name__']
Raymond Hettingera4f52b12009-03-02 22:28:31 +0000217 namespace = dict(itemgetter=_itemgetter, __name__='namedtuple_%s' % typename,
218 OrderedDict=OrderedDict)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000219 try:
220 exec(template, namespace)
221 except SyntaxError as e:
Christian Heimes99170a52007-12-19 02:07:34 +0000222 raise SyntaxError(e.msg + ':\n' + template) from e
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000223 result = namespace[typename]
224
225 # For pickling to work, the __module__ variable needs to be set to the frame
226 # where the named tuple is created. Bypass this step in enviroments where
227 # sys._getframe is not defined (Jython for example).
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000228 if hasattr(_sys, '_getframe'):
Raymond Hettinger0f055172009-01-27 10:06:09 +0000229 result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__')
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000230
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000231 return result
Guido van Rossumd8faa362007-04-27 19:54:29 +0000232
Guido van Rossumd8faa362007-04-27 19:54:29 +0000233
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000234########################################################################
235### Counter
236########################################################################
237
238class Counter(dict):
239 '''Dict subclass for counting hashable items. Sometimes called a bag
240 or multiset. Elements are stored as dictionary keys and their counts
241 are stored as dictionary values.
242
243 >>> c = Counter('abracadabra') # count elements from a string
244
245 >>> c.most_common(3) # three most common elements
246 [('a', 5), ('r', 2), ('b', 2)]
247 >>> sorted(c) # list all unique elements
248 ['a', 'b', 'c', 'd', 'r']
249 >>> ''.join(sorted(c.elements())) # list elements with repetitions
250 'aaaaabbcdrr'
251 >>> sum(c.values()) # total of all counts
252 11
253
254 >>> c['a'] # count of letter 'a'
255 5
256 >>> for elem in 'shazam': # update counts from an iterable
257 ... c[elem] += 1 # by adding 1 to each element's count
258 >>> c['a'] # now there are seven 'a'
259 7
260 >>> del c['r'] # remove all 'r'
261 >>> c['r'] # now there are zero 'r'
262 0
263
264 >>> d = Counter('simsalabim') # make another counter
265 >>> c.update(d) # add in the second counter
266 >>> c['a'] # now there are nine 'a'
267 9
268
269 >>> c.clear() # empty the counter
270 >>> c
271 Counter()
272
273 Note: If a count is set to zero or reduced to zero, it will remain
274 in the counter until the entry is deleted or the counter is cleared:
275
276 >>> c = Counter('aaabbc')
277 >>> c['b'] -= 2 # reduce the count of 'b' by two
278 >>> c.most_common() # 'b' is still in, but its count is zero
279 [('a', 3), ('c', 1), ('b', 0)]
280
281 '''
282 # References:
283 # http://en.wikipedia.org/wiki/Multiset
284 # http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html
285 # http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm
286 # http://code.activestate.com/recipes/259174/
287 # Knuth, TAOCP Vol. II section 4.6.3
288
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000289 def __init__(self, iterable=None, **kwds):
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000290 '''Create a new, empty Counter object. And if given, count elements
291 from an input iterable. Or, initialize the count from another mapping
292 of elements to their counts.
293
294 >>> c = Counter() # a new, empty counter
295 >>> c = Counter('gallahad') # a new counter from an iterable
296 >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000297 >>> c = Counter(a=4, b=2) # a new counter from keyword args
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000298
299 '''
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000300 self.update(iterable, **kwds)
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000301
302 def __missing__(self, key):
303 'The count of elements not in the Counter is zero.'
304 # Needed so that self[missing_item] does not raise KeyError
305 return 0
306
307 def most_common(self, n=None):
308 '''List the n most common elements and their counts from the most
309 common to the least. If n is None, then list all element counts.
310
311 >>> Counter('abracadabra').most_common(3)
312 [('a', 5), ('r', 2), ('b', 2)]
313
314 '''
315 # Emulate Bag.sortedByCount from Smalltalk
316 if n is None:
317 return sorted(self.items(), key=_itemgetter(1), reverse=True)
318 return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
319
320 def elements(self):
321 '''Iterator over elements repeating each as many times as its count.
322
323 >>> c = Counter('ABCABC')
324 >>> sorted(c.elements())
325 ['A', 'A', 'B', 'B', 'C', 'C']
326
327 # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1
328 >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
329 >>> product = 1
330 >>> for factor in prime_factors.elements(): # loop over factors
331 ... product *= factor # and multiply them
332 >>> product
333 1836
334
335 Note, if an element's count has been set to zero or is a negative
336 number, elements() will ignore it.
337
338 '''
339 # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
340 return _chain.from_iterable(_starmap(_repeat, self.items()))
341
342 # Override dict methods where necessary
343
344 @classmethod
345 def fromkeys(cls, iterable, v=None):
346 # There is no equivalent method for counters because setting v=1
347 # means that no element can have a count greater than one.
348 raise NotImplementedError(
349 'Counter.fromkeys() is undefined. Use Counter(iterable) instead.')
350
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000351 def update(self, iterable=None, **kwds):
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000352 '''Like dict.update() but add counts instead of replacing them.
353
354 Source can be an iterable, a dictionary, or another Counter instance.
355
356 >>> c = Counter('which')
357 >>> c.update('witch') # add elements from another iterable
358 >>> d = Counter('watch')
359 >>> c.update(d) # add elements from another counter
360 >>> c['h'] # four 'h' in which, witch, and watch
361 4
362
363 '''
364 # The regular dict.update() operation makes no sense here because the
365 # replace behavior results in the some of original untouched counts
366 # being mixed-in with all of the other counts for a mismash that
367 # doesn't have a straight-forward interpretation in most counting
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000368 # contexts. Instead, we implement straight-addition. Both the inputs
369 # and outputs are allowed to contain zero and negative counts.
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000370
371 if iterable is not None:
372 if isinstance(iterable, Mapping):
Raymond Hettingerdd01f8f2009-01-22 09:09:55 +0000373 if self:
374 for elem, count in iterable.items():
375 self[elem] += count
376 else:
377 dict.update(self, iterable) # fast path when counter is empty
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000378 else:
379 for elem in iterable:
380 self[elem] += 1
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000381 if kwds:
382 self.update(kwds)
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000383
384 def copy(self):
385 'Like dict.copy() but returns a Counter instance instead of a dict.'
386 return Counter(self)
387
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000388 def __delitem__(self, elem):
389 'Like dict.__delitem__() but does not raise KeyError for missing values.'
390 if elem in self:
391 dict.__delitem__(self, elem)
392
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000393 def __repr__(self):
394 if not self:
395 return '%s()' % self.__class__.__name__
396 items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
397 return '%s({%s})' % (self.__class__.__name__, items)
398
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000399 # Multiset-style mathematical operations discussed in:
400 # Knuth TAOCP Volume II section 4.6.3 exercise 19
401 # and at http://en.wikipedia.org/wiki/Multiset
402 #
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000403 # Outputs guaranteed to only include positive counts.
404 #
405 # To strip negative and zero counts, add-in an empty counter:
406 # c += Counter()
407
408 def __add__(self, other):
409 '''Add counts from two counters.
410
411 >>> Counter('abbb') + Counter('bcc')
412 Counter({'b': 4, 'c': 2, 'a': 1})
413
414 '''
415 if not isinstance(other, Counter):
416 return NotImplemented
417 result = Counter()
418 for elem in set(self) | set(other):
419 newcount = self[elem] + other[elem]
420 if newcount > 0:
421 result[elem] = newcount
422 return result
423
424 def __sub__(self, other):
425 ''' Subtract count, but keep only results with positive counts.
426
427 >>> Counter('abbbc') - Counter('bccd')
428 Counter({'b': 2, 'a': 1})
429
430 '''
431 if not isinstance(other, Counter):
432 return NotImplemented
433 result = Counter()
Raymond Hettingere0d1b9f2009-01-21 20:36:27 +0000434 for elem in set(self) | set(other):
435 newcount = self[elem] - other[elem]
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000436 if newcount > 0:
437 result[elem] = newcount
438 return result
439
440 def __or__(self, other):
441 '''Union is the maximum of value in either of the input counters.
442
443 >>> Counter('abbb') | Counter('bcc')
444 Counter({'b': 3, 'c': 2, 'a': 1})
445
446 '''
447 if not isinstance(other, Counter):
448 return NotImplemented
449 _max = max
450 result = Counter()
451 for elem in set(self) | set(other):
452 newcount = _max(self[elem], other[elem])
453 if newcount > 0:
454 result[elem] = newcount
455 return result
456
457 def __and__(self, other):
458 ''' Intersection is the minimum of corresponding counts.
459
460 >>> Counter('abbb') & Counter('bcc')
461 Counter({'b': 1})
462
463 '''
464 if not isinstance(other, Counter):
465 return NotImplemented
466 _min = min
467 result = Counter()
468 if len(self) < len(other):
469 self, other = other, self
470 for elem in filter(self.__contains__, other):
471 newcount = _min(self[elem], other[elem])
472 if newcount > 0:
473 result[elem] = newcount
474 return result
475
Guido van Rossumd8faa362007-04-27 19:54:29 +0000476
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000477################################################################################
478### UserDict
479################################################################################
Guido van Rossumd8faa362007-04-27 19:54:29 +0000480
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000481class UserDict(MutableMapping):
482
483 # Start by filling-out the abstract methods
484 def __init__(self, dict=None, **kwargs):
485 self.data = {}
486 if dict is not None:
487 self.update(dict)
488 if len(kwargs):
489 self.update(kwargs)
490 def __len__(self): return len(self.data)
491 def __getitem__(self, key):
492 if key in self.data:
493 return self.data[key]
494 if hasattr(self.__class__, "__missing__"):
495 return self.__class__.__missing__(self, key)
496 raise KeyError(key)
497 def __setitem__(self, key, item): self.data[key] = item
498 def __delitem__(self, key): del self.data[key]
499 def __iter__(self):
500 return iter(self.data)
501
Raymond Hettinger554c8b82008-02-05 22:54:43 +0000502 # Modify __contains__ to work correctly when __missing__ is present
503 def __contains__(self, key):
504 return key in self.data
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000505
506 # Now, add the methods in dicts but not in MutableMapping
507 def __repr__(self): return repr(self.data)
508 def copy(self):
509 if self.__class__ is UserDict:
510 return UserDict(self.data.copy())
511 import copy
512 data = self.data
513 try:
514 self.data = {}
515 c = copy.copy(self)
516 finally:
517 self.data = data
518 c.update(self)
519 return c
520 @classmethod
521 def fromkeys(cls, iterable, value=None):
522 d = cls()
523 for key in iterable:
524 d[key] = value
525 return d
526
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000527
528
529################################################################################
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000530### UserList
531################################################################################
532
533class UserList(MutableSequence):
534 """A more or less complete user-defined wrapper around list objects."""
535 def __init__(self, initlist=None):
536 self.data = []
537 if initlist is not None:
538 # XXX should this accept an arbitrary sequence?
539 if type(initlist) == type(self.data):
540 self.data[:] = initlist
541 elif isinstance(initlist, UserList):
542 self.data[:] = initlist.data[:]
543 else:
544 self.data = list(initlist)
545 def __repr__(self): return repr(self.data)
546 def __lt__(self, other): return self.data < self.__cast(other)
547 def __le__(self, other): return self.data <= self.__cast(other)
548 def __eq__(self, other): return self.data == self.__cast(other)
549 def __ne__(self, other): return self.data != self.__cast(other)
550 def __gt__(self, other): return self.data > self.__cast(other)
551 def __ge__(self, other): return self.data >= self.__cast(other)
552 def __cast(self, other):
553 return other.data if isinstance(other, UserList) else other
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000554 def __contains__(self, item): return item in self.data
555 def __len__(self): return len(self.data)
556 def __getitem__(self, i): return self.data[i]
557 def __setitem__(self, i, item): self.data[i] = item
558 def __delitem__(self, i): del self.data[i]
559 def __add__(self, other):
560 if isinstance(other, UserList):
561 return self.__class__(self.data + other.data)
562 elif isinstance(other, type(self.data)):
563 return self.__class__(self.data + other)
564 return self.__class__(self.data + list(other))
565 def __radd__(self, other):
566 if isinstance(other, UserList):
567 return self.__class__(other.data + self.data)
568 elif isinstance(other, type(self.data)):
569 return self.__class__(other + self.data)
570 return self.__class__(list(other) + self.data)
571 def __iadd__(self, other):
572 if isinstance(other, UserList):
573 self.data += other.data
574 elif isinstance(other, type(self.data)):
575 self.data += other
576 else:
577 self.data += list(other)
578 return self
579 def __mul__(self, n):
580 return self.__class__(self.data*n)
581 __rmul__ = __mul__
582 def __imul__(self, n):
583 self.data *= n
584 return self
585 def append(self, item): self.data.append(item)
586 def insert(self, i, item): self.data.insert(i, item)
587 def pop(self, i=-1): return self.data.pop(i)
588 def remove(self, item): self.data.remove(item)
589 def count(self, item): return self.data.count(item)
590 def index(self, item, *args): return self.data.index(item, *args)
591 def reverse(self): self.data.reverse()
592 def sort(self, *args, **kwds): self.data.sort(*args, **kwds)
593 def extend(self, other):
594 if isinstance(other, UserList):
595 self.data.extend(other.data)
596 else:
597 self.data.extend(other)
598
599
600
601################################################################################
Raymond Hettingerb3a65f82008-02-21 22:11:37 +0000602### UserString
603################################################################################
604
605class UserString(Sequence):
606 def __init__(self, seq):
607 if isinstance(seq, str):
608 self.data = seq
609 elif isinstance(seq, UserString):
610 self.data = seq.data[:]
611 else:
612 self.data = str(seq)
613 def __str__(self): return str(self.data)
614 def __repr__(self): return repr(self.data)
615 def __int__(self): return int(self.data)
Raymond Hettingerb3a65f82008-02-21 22:11:37 +0000616 def __float__(self): return float(self.data)
617 def __complex__(self): return complex(self.data)
618 def __hash__(self): return hash(self.data)
619
620 def __eq__(self, string):
621 if isinstance(string, UserString):
622 return self.data == string.data
623 return self.data == string
624 def __ne__(self, string):
625 if isinstance(string, UserString):
626 return self.data != string.data
627 return self.data != string
628 def __lt__(self, string):
629 if isinstance(string, UserString):
630 return self.data < string.data
631 return self.data < string
632 def __le__(self, string):
633 if isinstance(string, UserString):
634 return self.data <= string.data
635 return self.data <= string
636 def __gt__(self, string):
637 if isinstance(string, UserString):
638 return self.data > string.data
639 return self.data > string
640 def __ge__(self, string):
641 if isinstance(string, UserString):
642 return self.data >= string.data
643 return self.data >= string
644
645 def __contains__(self, char):
646 if isinstance(char, UserString):
647 char = char.data
648 return char in self.data
649
650 def __len__(self): return len(self.data)
651 def __getitem__(self, index): return self.__class__(self.data[index])
652 def __add__(self, other):
653 if isinstance(other, UserString):
654 return self.__class__(self.data + other.data)
655 elif isinstance(other, str):
656 return self.__class__(self.data + other)
657 return self.__class__(self.data + str(other))
658 def __radd__(self, other):
659 if isinstance(other, str):
660 return self.__class__(other + self.data)
661 return self.__class__(str(other) + self.data)
662 def __mul__(self, n):
663 return self.__class__(self.data*n)
664 __rmul__ = __mul__
665 def __mod__(self, args):
666 return self.__class__(self.data % args)
667
668 # the following methods are defined in alphabetical order:
669 def capitalize(self): return self.__class__(self.data.capitalize())
670 def center(self, width, *args):
671 return self.__class__(self.data.center(width, *args))
672 def count(self, sub, start=0, end=_sys.maxsize):
673 if isinstance(sub, UserString):
674 sub = sub.data
675 return self.data.count(sub, start, end)
676 def encode(self, encoding=None, errors=None): # XXX improve this?
677 if encoding:
678 if errors:
679 return self.__class__(self.data.encode(encoding, errors))
680 return self.__class__(self.data.encode(encoding))
681 return self.__class__(self.data.encode())
682 def endswith(self, suffix, start=0, end=_sys.maxsize):
683 return self.data.endswith(suffix, start, end)
684 def expandtabs(self, tabsize=8):
685 return self.__class__(self.data.expandtabs(tabsize))
686 def find(self, sub, start=0, end=_sys.maxsize):
687 if isinstance(sub, UserString):
688 sub = sub.data
689 return self.data.find(sub, start, end)
690 def format(self, *args, **kwds):
691 return self.data.format(*args, **kwds)
692 def index(self, sub, start=0, end=_sys.maxsize):
693 return self.data.index(sub, start, end)
694 def isalpha(self): return self.data.isalpha()
695 def isalnum(self): return self.data.isalnum()
696 def isdecimal(self): return self.data.isdecimal()
697 def isdigit(self): return self.data.isdigit()
698 def isidentifier(self): return self.data.isidentifier()
699 def islower(self): return self.data.islower()
700 def isnumeric(self): return self.data.isnumeric()
701 def isspace(self): return self.data.isspace()
702 def istitle(self): return self.data.istitle()
703 def isupper(self): return self.data.isupper()
704 def join(self, seq): return self.data.join(seq)
705 def ljust(self, width, *args):
706 return self.__class__(self.data.ljust(width, *args))
707 def lower(self): return self.__class__(self.data.lower())
708 def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars))
709 def partition(self, sep):
710 return self.data.partition(sep)
711 def replace(self, old, new, maxsplit=-1):
712 if isinstance(old, UserString):
713 old = old.data
714 if isinstance(new, UserString):
715 new = new.data
716 return self.__class__(self.data.replace(old, new, maxsplit))
717 def rfind(self, sub, start=0, end=_sys.maxsize):
718 return self.data.rfind(sub, start, end)
719 def rindex(self, sub, start=0, end=_sys.maxsize):
720 return self.data.rindex(sub, start, end)
721 def rjust(self, width, *args):
722 return self.__class__(self.data.rjust(width, *args))
723 def rpartition(self, sep):
724 return self.data.rpartition(sep)
725 def rstrip(self, chars=None):
726 return self.__class__(self.data.rstrip(chars))
727 def split(self, sep=None, maxsplit=-1):
728 return self.data.split(sep, maxsplit)
729 def rsplit(self, sep=None, maxsplit=-1):
730 return self.data.rsplit(sep, maxsplit)
731 def splitlines(self, keepends=0): return self.data.splitlines(keepends)
732 def startswith(self, prefix, start=0, end=_sys.maxsize):
733 return self.data.startswith(prefix, start, end)
734 def strip(self, chars=None): return self.__class__(self.data.strip(chars))
735 def swapcase(self): return self.__class__(self.data.swapcase())
736 def title(self): return self.__class__(self.data.title())
737 def translate(self, *args):
738 return self.__class__(self.data.translate(*args))
739 def upper(self): return self.__class__(self.data.upper())
740 def zfill(self, width): return self.__class__(self.data.zfill(width))
741
742
743
744################################################################################
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000745### Simple tests
746################################################################################
Guido van Rossumd8faa362007-04-27 19:54:29 +0000747
748if __name__ == '__main__':
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000749 # verify that instances can be pickled
Guido van Rossum99603b02007-07-20 00:22:32 +0000750 from pickle import loads, dumps
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000751 Point = namedtuple('Point', 'x, y', True)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000752 p = Point(x=10, y=20)
753 assert p == loads(dumps(p))
754
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000755 # test and demonstrate ability to override methods
Christian Heimes043d6f62008-01-07 17:19:16 +0000756 class Point(namedtuple('Point', 'x y')):
Christian Heimes25bb7832008-01-11 16:17:00 +0000757 __slots__ = ()
Christian Heimes043d6f62008-01-07 17:19:16 +0000758 @property
759 def hypot(self):
760 return (self.x ** 2 + self.y ** 2) ** 0.5
Christian Heimes790c8232008-01-07 21:14:23 +0000761 def __str__(self):
Christian Heimes25bb7832008-01-11 16:17:00 +0000762 return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot)
Christian Heimes043d6f62008-01-07 17:19:16 +0000763
Christian Heimes25bb7832008-01-11 16:17:00 +0000764 for p in Point(3, 4), Point(14, 5/7.):
Christian Heimes790c8232008-01-07 21:14:23 +0000765 print (p)
Christian Heimes043d6f62008-01-07 17:19:16 +0000766
767 class Point(namedtuple('Point', 'x y')):
768 'Point class with optimized _make() and _replace() without error-checking'
Christian Heimes25bb7832008-01-11 16:17:00 +0000769 __slots__ = ()
Christian Heimes043d6f62008-01-07 17:19:16 +0000770 _make = classmethod(tuple.__new__)
771 def _replace(self, _map=map, **kwds):
Christian Heimes2380ac72008-01-09 00:17:24 +0000772 return self._make(_map(kwds.get, ('x', 'y'), self))
Christian Heimes043d6f62008-01-07 17:19:16 +0000773
774 print(Point(11, 22)._replace(x=100))
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000775
Christian Heimes25bb7832008-01-11 16:17:00 +0000776 Point3D = namedtuple('Point3D', Point._fields + ('z',))
777 print(Point3D.__doc__)
778
Guido van Rossumd8faa362007-04-27 19:54:29 +0000779 import doctest
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000780 TestResults = namedtuple('TestResults', 'failed attempted')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000781 print(TestResults(*doctest.testmod()))