blob: f1b62c7f94742d377d374664f18aa7a524562424 [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):
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 Hettinger08c70cf2009-03-03 20:47:29 +000025 try:
Raymond Hettingerdc879f02009-03-19 20:30:56 +000026 self.__end
Raymond Hettinger08c70cf2009-03-03 20:47:29 +000027 except AttributeError:
Raymond Hettingerdc879f02009-03-19 20:30:56 +000028 self.clear()
Raymond Hettinger2d32f632009-03-02 21:24:57 +000029 self.update(*args, **kwds)
30
31 def clear(self):
Raymond Hettingerdc879f02009-03-19 20:30:56 +000032 self.__end = end = []
33 end += [None, end, end] # sentinel node for doubly linked list
34 self.__map = {} # key --> [key, prev, next]
Raymond Hettinger2d32f632009-03-02 21:24:57 +000035 dict.clear(self)
36
37 def __setitem__(self, key, value):
38 if key not in self:
Raymond Hettingerdc879f02009-03-19 20:30:56 +000039 end = self.__end
40 curr = end[1]
41 curr[2] = end[1] = self.__map[key] = [key, curr, end]
Raymond Hettinger2d32f632009-03-02 21:24:57 +000042 dict.__setitem__(self, key, value)
43
44 def __delitem__(self, key):
45 dict.__delitem__(self, key)
Raymond Hettingerdc879f02009-03-19 20:30:56 +000046 key, prev, next = self.__map.pop(key)
47 prev[2] = next
48 next[1] = prev
Raymond Hettinger2d32f632009-03-02 21:24:57 +000049
50 def __iter__(self):
Raymond Hettingerdc879f02009-03-19 20:30:56 +000051 end = self.__end
52 curr = end[2]
53 while curr is not end:
54 yield curr[0]
55 curr = curr[2]
Raymond Hettinger2d32f632009-03-02 21:24:57 +000056
57 def __reversed__(self):
Raymond Hettingerdc879f02009-03-19 20:30:56 +000058 end = self.__end
59 curr = end[1]
60 while curr is not end:
61 yield curr[0]
62 curr = curr[1]
Raymond Hettinger2d32f632009-03-02 21:24:57 +000063
Raymond Hettingerdc879f02009-03-19 20:30:56 +000064 def popitem(self, last=True):
Raymond Hettinger2d32f632009-03-02 21:24:57 +000065 if not self:
66 raise KeyError('dictionary is empty')
Raymond Hettingerdc879f02009-03-19 20:30:56 +000067 key = next(reversed(self)) if last else next(iter(self))
68 value = self.pop(key)
Raymond Hettinger2d32f632009-03-02 21:24:57 +000069 return key, value
70
71 def __reduce__(self):
72 items = [[k, self[k]] for k in self]
Raymond Hettingerdc879f02009-03-19 20:30:56 +000073 tmp = self.__map, self.__end
74 del self.__map, self.__end
Raymond Hettinger2d32f632009-03-02 21:24:57 +000075 inst_dict = vars(self).copy()
Raymond Hettingerdc879f02009-03-19 20:30:56 +000076 self.__map, self.__end = tmp
Raymond Hettinger14b89ff2009-03-03 22:20:56 +000077 if inst_dict:
78 return (self.__class__, (items,), inst_dict)
79 return self.__class__, (items,)
Raymond Hettinger2d32f632009-03-02 21:24:57 +000080
81 setdefault = MutableMapping.setdefault
82 update = MutableMapping.update
83 pop = MutableMapping.pop
84 keys = MutableMapping.keys
85 values = MutableMapping.values
86 items = MutableMapping.items
87
88 def __repr__(self):
89 if not self:
90 return '%s()' % (self.__class__.__name__,)
91 return '%s(%r)' % (self.__class__.__name__, list(self.items()))
92
93 def copy(self):
94 return self.__class__(self)
95
96 @classmethod
97 def fromkeys(cls, iterable, value=None):
98 d = cls()
99 for key in iterable:
100 d[key] = value
101 return d
102
103 def __eq__(self, other):
104 if isinstance(other, OrderedDict):
Raymond Hettingerea9f8db2009-03-02 21:28:41 +0000105 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 +0000106 return dict.__eq__(self, other)
107
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000108
Christian Heimes99170a52007-12-19 02:07:34 +0000109
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000110################################################################################
111### namedtuple
112################################################################################
113
Benjamin Petersona86f2c02009-02-10 02:41:10 +0000114def namedtuple(typename, field_names, verbose=False, rename=False):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000115 """Returns a new subclass of tuple with named fields.
116
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000117 >>> Point = namedtuple('Point', 'x y')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000118 >>> Point.__doc__ # docstring for the new class
Guido van Rossumd8faa362007-04-27 19:54:29 +0000119 'Point(x, y)'
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000120 >>> p = Point(11, y=22) # instantiate with positional args or keywords
Christian Heimes99170a52007-12-19 02:07:34 +0000121 >>> p[0] + p[1] # indexable like a plain tuple
Guido van Rossumd8faa362007-04-27 19:54:29 +0000122 33
Christian Heimes99170a52007-12-19 02:07:34 +0000123 >>> x, y = p # unpack like a regular tuple
Guido van Rossumd8faa362007-04-27 19:54:29 +0000124 >>> x, y
125 (11, 22)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000126 >>> p.x + p.y # fields also accessable by name
Guido van Rossumd8faa362007-04-27 19:54:29 +0000127 33
Christian Heimes0449f632007-12-15 01:27:15 +0000128 >>> d = p._asdict() # convert to a dictionary
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000129 >>> d['x']
130 11
131 >>> Point(**d) # convert from a dictionary
Guido van Rossumd8faa362007-04-27 19:54:29 +0000132 Point(x=11, y=22)
Christian Heimes0449f632007-12-15 01:27:15 +0000133 >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000134 Point(x=100, y=22)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000135
136 """
137
Christian Heimes2380ac72008-01-09 00:17:24 +0000138 # Parse and validate the field names. Validation serves two purposes,
139 # generating informative error messages and preventing template injection attacks.
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000140 if isinstance(field_names, str):
141 field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +0000142 field_names = tuple(map(str, field_names))
Benjamin Petersona86f2c02009-02-10 02:41:10 +0000143 if rename:
144 names = list(field_names)
145 seen = set()
146 for i, name in enumerate(names):
147 if (not all(c.isalnum() or c=='_' for c in name) or _iskeyword(name)
148 or not name or name[0].isdigit() or name.startswith('_')
149 or name in seen):
150 names[i] = '_%d' % (i+1)
151 seen.add(name)
152 field_names = tuple(names)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000153 for name in (typename,) + field_names:
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000154 if not all(c.isalnum() or c=='_' for c in name):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000155 raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
156 if _iskeyword(name):
157 raise ValueError('Type names and field names cannot be a keyword: %r' % name)
158 if name[0].isdigit():
159 raise ValueError('Type names and field names cannot start with a number: %r' % name)
160 seen_names = set()
161 for name in field_names:
Benjamin Petersona86f2c02009-02-10 02:41:10 +0000162 if name.startswith('_') and not rename:
Christian Heimes0449f632007-12-15 01:27:15 +0000163 raise ValueError('Field names cannot start with an underscore: %r' % name)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000164 if name in seen_names:
165 raise ValueError('Encountered duplicate field name: %r' % name)
166 seen_names.add(name)
167
168 # Create and fill-in the class template
Christian Heimesfaf2f632008-01-06 16:59:19 +0000169 numfields = len(field_names)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000170 argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000171 reprtxt = ', '.join('%s=%%r' % name for name in field_names)
172 template = '''class %(typename)s(tuple):
Christian Heimes0449f632007-12-15 01:27:15 +0000173 '%(typename)s(%(argtxt)s)' \n
174 __slots__ = () \n
Christian Heimesfaf2f632008-01-06 16:59:19 +0000175 _fields = %(field_names)r \n
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000176 def __new__(cls, %(argtxt)s):
Christian Heimes0449f632007-12-15 01:27:15 +0000177 return tuple.__new__(cls, (%(argtxt)s)) \n
Christian Heimesfaf2f632008-01-06 16:59:19 +0000178 @classmethod
Christian Heimes043d6f62008-01-07 17:19:16 +0000179 def _make(cls, iterable, new=tuple.__new__, len=len):
Christian Heimesfaf2f632008-01-06 16:59:19 +0000180 'Make a new %(typename)s object from a sequence or iterable'
Christian Heimes043d6f62008-01-07 17:19:16 +0000181 result = new(cls, iterable)
Christian Heimesfaf2f632008-01-06 16:59:19 +0000182 if len(result) != %(numfields)d:
183 raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
184 return result \n
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000185 def __repr__(self):
Christian Heimes0449f632007-12-15 01:27:15 +0000186 return '%(typename)s(%(reprtxt)s)' %% self \n
Raymond Hettingera4f52b12009-03-02 22:28:31 +0000187 def _asdict(self):
188 'Return a new OrderedDict which maps field names to their values'
189 return OrderedDict(zip(self._fields, self)) \n
Christian Heimes0449f632007-12-15 01:27:15 +0000190 def _replace(self, **kwds):
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000191 'Return a new %(typename)s object replacing specified fields with new values'
Christian Heimesfaf2f632008-01-06 16:59:19 +0000192 result = self._make(map(kwds.pop, %(field_names)r, self))
193 if kwds:
194 raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000195 return result \n
196 def __getnewargs__(self):
197 return tuple(self) \n\n''' % locals()
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000198 for i, name in enumerate(field_names):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000199 template += ' %s = property(itemgetter(%d))\n' % (name, i)
200 if verbose:
201 print(template)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000202
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000203 # Execute the template string in a temporary namespace and
204 # support tracing utilities by setting a value for frame.f_globals['__name__']
Raymond Hettingera4f52b12009-03-02 22:28:31 +0000205 namespace = dict(itemgetter=_itemgetter, __name__='namedtuple_%s' % typename,
206 OrderedDict=OrderedDict)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000207 try:
208 exec(template, namespace)
209 except SyntaxError as e:
Christian Heimes99170a52007-12-19 02:07:34 +0000210 raise SyntaxError(e.msg + ':\n' + template) from e
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000211 result = namespace[typename]
212
213 # For pickling to work, the __module__ variable needs to be set to the frame
214 # where the named tuple is created. Bypass this step in enviroments where
215 # sys._getframe is not defined (Jython for example).
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000216 if hasattr(_sys, '_getframe'):
Raymond Hettinger0f055172009-01-27 10:06:09 +0000217 result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__')
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000218
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000219 return result
Guido van Rossumd8faa362007-04-27 19:54:29 +0000220
Guido van Rossumd8faa362007-04-27 19:54:29 +0000221
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000222########################################################################
223### Counter
224########################################################################
225
226class Counter(dict):
227 '''Dict subclass for counting hashable items. Sometimes called a bag
228 or multiset. Elements are stored as dictionary keys and their counts
229 are stored as dictionary values.
230
231 >>> c = Counter('abracadabra') # count elements from a string
232
233 >>> c.most_common(3) # three most common elements
234 [('a', 5), ('r', 2), ('b', 2)]
235 >>> sorted(c) # list all unique elements
236 ['a', 'b', 'c', 'd', 'r']
237 >>> ''.join(sorted(c.elements())) # list elements with repetitions
238 'aaaaabbcdrr'
239 >>> sum(c.values()) # total of all counts
240 11
241
242 >>> c['a'] # count of letter 'a'
243 5
244 >>> for elem in 'shazam': # update counts from an iterable
245 ... c[elem] += 1 # by adding 1 to each element's count
246 >>> c['a'] # now there are seven 'a'
247 7
248 >>> del c['r'] # remove all 'r'
249 >>> c['r'] # now there are zero 'r'
250 0
251
252 >>> d = Counter('simsalabim') # make another counter
253 >>> c.update(d) # add in the second counter
254 >>> c['a'] # now there are nine 'a'
255 9
256
257 >>> c.clear() # empty the counter
258 >>> c
259 Counter()
260
261 Note: If a count is set to zero or reduced to zero, it will remain
262 in the counter until the entry is deleted or the counter is cleared:
263
264 >>> c = Counter('aaabbc')
265 >>> c['b'] -= 2 # reduce the count of 'b' by two
266 >>> c.most_common() # 'b' is still in, but its count is zero
267 [('a', 3), ('c', 1), ('b', 0)]
268
269 '''
270 # References:
271 # http://en.wikipedia.org/wiki/Multiset
272 # http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html
273 # http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm
274 # http://code.activestate.com/recipes/259174/
275 # Knuth, TAOCP Vol. II section 4.6.3
276
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000277 def __init__(self, iterable=None, **kwds):
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000278 '''Create a new, empty Counter object. And if given, count elements
279 from an input iterable. Or, initialize the count from another mapping
280 of elements to their counts.
281
282 >>> c = Counter() # a new, empty counter
283 >>> c = Counter('gallahad') # a new counter from an iterable
284 >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000285 >>> c = Counter(a=4, b=2) # a new counter from keyword args
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000286
287 '''
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000288 self.update(iterable, **kwds)
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000289
290 def __missing__(self, key):
291 'The count of elements not in the Counter is zero.'
292 # Needed so that self[missing_item] does not raise KeyError
293 return 0
294
295 def most_common(self, n=None):
296 '''List the n most common elements and their counts from the most
297 common to the least. If n is None, then list all element counts.
298
299 >>> Counter('abracadabra').most_common(3)
300 [('a', 5), ('r', 2), ('b', 2)]
301
302 '''
303 # Emulate Bag.sortedByCount from Smalltalk
304 if n is None:
305 return sorted(self.items(), key=_itemgetter(1), reverse=True)
306 return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
307
308 def elements(self):
309 '''Iterator over elements repeating each as many times as its count.
310
311 >>> c = Counter('ABCABC')
312 >>> sorted(c.elements())
313 ['A', 'A', 'B', 'B', 'C', 'C']
314
315 # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1
316 >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
317 >>> product = 1
318 >>> for factor in prime_factors.elements(): # loop over factors
319 ... product *= factor # and multiply them
320 >>> product
321 1836
322
323 Note, if an element's count has been set to zero or is a negative
324 number, elements() will ignore it.
325
326 '''
327 # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
328 return _chain.from_iterable(_starmap(_repeat, self.items()))
329
330 # Override dict methods where necessary
331
332 @classmethod
333 def fromkeys(cls, iterable, v=None):
334 # There is no equivalent method for counters because setting v=1
335 # means that no element can have a count greater than one.
336 raise NotImplementedError(
337 'Counter.fromkeys() is undefined. Use Counter(iterable) instead.')
338
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000339 def update(self, iterable=None, **kwds):
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000340 '''Like dict.update() but add counts instead of replacing them.
341
342 Source can be an iterable, a dictionary, or another Counter instance.
343
344 >>> c = Counter('which')
345 >>> c.update('witch') # add elements from another iterable
346 >>> d = Counter('watch')
347 >>> c.update(d) # add elements from another counter
348 >>> c['h'] # four 'h' in which, witch, and watch
349 4
350
351 '''
352 # The regular dict.update() operation makes no sense here because the
353 # replace behavior results in the some of original untouched counts
354 # being mixed-in with all of the other counts for a mismash that
355 # doesn't have a straight-forward interpretation in most counting
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000356 # contexts. Instead, we implement straight-addition. Both the inputs
357 # and outputs are allowed to contain zero and negative counts.
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000358
359 if iterable is not None:
360 if isinstance(iterable, Mapping):
Raymond Hettingerdd01f8f2009-01-22 09:09:55 +0000361 if self:
362 for elem, count in iterable.items():
363 self[elem] += count
364 else:
365 dict.update(self, iterable) # fast path when counter is empty
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000366 else:
367 for elem in iterable:
368 self[elem] += 1
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000369 if kwds:
370 self.update(kwds)
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000371
372 def copy(self):
373 'Like dict.copy() but returns a Counter instance instead of a dict.'
374 return Counter(self)
375
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000376 def __delitem__(self, elem):
377 'Like dict.__delitem__() but does not raise KeyError for missing values.'
378 if elem in self:
379 dict.__delitem__(self, elem)
380
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000381 def __repr__(self):
382 if not self:
383 return '%s()' % self.__class__.__name__
384 items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
385 return '%s({%s})' % (self.__class__.__name__, items)
386
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000387 # Multiset-style mathematical operations discussed in:
388 # Knuth TAOCP Volume II section 4.6.3 exercise 19
389 # and at http://en.wikipedia.org/wiki/Multiset
390 #
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000391 # Outputs guaranteed to only include positive counts.
392 #
393 # To strip negative and zero counts, add-in an empty counter:
394 # c += Counter()
395
396 def __add__(self, other):
397 '''Add counts from two counters.
398
399 >>> Counter('abbb') + Counter('bcc')
400 Counter({'b': 4, 'c': 2, 'a': 1})
401
402 '''
403 if not isinstance(other, Counter):
404 return NotImplemented
405 result = Counter()
406 for elem in set(self) | set(other):
407 newcount = self[elem] + other[elem]
408 if newcount > 0:
409 result[elem] = newcount
410 return result
411
412 def __sub__(self, other):
413 ''' Subtract count, but keep only results with positive counts.
414
415 >>> Counter('abbbc') - Counter('bccd')
416 Counter({'b': 2, 'a': 1})
417
418 '''
419 if not isinstance(other, Counter):
420 return NotImplemented
421 result = Counter()
Raymond Hettingere0d1b9f2009-01-21 20:36:27 +0000422 for elem in set(self) | set(other):
423 newcount = self[elem] - other[elem]
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000424 if newcount > 0:
425 result[elem] = newcount
426 return result
427
428 def __or__(self, other):
429 '''Union is the maximum of value in either of the input counters.
430
431 >>> Counter('abbb') | Counter('bcc')
432 Counter({'b': 3, 'c': 2, 'a': 1})
433
434 '''
435 if not isinstance(other, Counter):
436 return NotImplemented
437 _max = max
438 result = Counter()
439 for elem in set(self) | set(other):
440 newcount = _max(self[elem], other[elem])
441 if newcount > 0:
442 result[elem] = newcount
443 return result
444
445 def __and__(self, other):
446 ''' Intersection is the minimum of corresponding counts.
447
448 >>> Counter('abbb') & Counter('bcc')
449 Counter({'b': 1})
450
451 '''
452 if not isinstance(other, Counter):
453 return NotImplemented
454 _min = min
455 result = Counter()
456 if len(self) < len(other):
457 self, other = other, self
458 for elem in filter(self.__contains__, other):
459 newcount = _min(self[elem], other[elem])
460 if newcount > 0:
461 result[elem] = newcount
462 return result
463
Guido van Rossumd8faa362007-04-27 19:54:29 +0000464
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000465################################################################################
466### UserDict
467################################################################################
Guido van Rossumd8faa362007-04-27 19:54:29 +0000468
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000469class UserDict(MutableMapping):
470
471 # Start by filling-out the abstract methods
472 def __init__(self, dict=None, **kwargs):
473 self.data = {}
474 if dict is not None:
475 self.update(dict)
476 if len(kwargs):
477 self.update(kwargs)
478 def __len__(self): return len(self.data)
479 def __getitem__(self, key):
480 if key in self.data:
481 return self.data[key]
482 if hasattr(self.__class__, "__missing__"):
483 return self.__class__.__missing__(self, key)
484 raise KeyError(key)
485 def __setitem__(self, key, item): self.data[key] = item
486 def __delitem__(self, key): del self.data[key]
487 def __iter__(self):
488 return iter(self.data)
489
Raymond Hettinger554c8b82008-02-05 22:54:43 +0000490 # Modify __contains__ to work correctly when __missing__ is present
491 def __contains__(self, key):
492 return key in self.data
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000493
494 # Now, add the methods in dicts but not in MutableMapping
495 def __repr__(self): return repr(self.data)
496 def copy(self):
497 if self.__class__ is UserDict:
498 return UserDict(self.data.copy())
499 import copy
500 data = self.data
501 try:
502 self.data = {}
503 c = copy.copy(self)
504 finally:
505 self.data = data
506 c.update(self)
507 return c
508 @classmethod
509 def fromkeys(cls, iterable, value=None):
510 d = cls()
511 for key in iterable:
512 d[key] = value
513 return d
514
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000515
516
517################################################################################
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000518### UserList
519################################################################################
520
521class UserList(MutableSequence):
522 """A more or less complete user-defined wrapper around list objects."""
523 def __init__(self, initlist=None):
524 self.data = []
525 if initlist is not None:
526 # XXX should this accept an arbitrary sequence?
527 if type(initlist) == type(self.data):
528 self.data[:] = initlist
529 elif isinstance(initlist, UserList):
530 self.data[:] = initlist.data[:]
531 else:
532 self.data = list(initlist)
533 def __repr__(self): return repr(self.data)
534 def __lt__(self, other): return self.data < self.__cast(other)
535 def __le__(self, other): return self.data <= self.__cast(other)
536 def __eq__(self, other): return self.data == self.__cast(other)
537 def __ne__(self, other): return self.data != self.__cast(other)
538 def __gt__(self, other): return self.data > self.__cast(other)
539 def __ge__(self, other): return self.data >= self.__cast(other)
540 def __cast(self, other):
541 return other.data if isinstance(other, UserList) else other
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000542 def __contains__(self, item): return item in self.data
543 def __len__(self): return len(self.data)
544 def __getitem__(self, i): return self.data[i]
545 def __setitem__(self, i, item): self.data[i] = item
546 def __delitem__(self, i): del self.data[i]
547 def __add__(self, other):
548 if isinstance(other, UserList):
549 return self.__class__(self.data + other.data)
550 elif isinstance(other, type(self.data)):
551 return self.__class__(self.data + other)
552 return self.__class__(self.data + list(other))
553 def __radd__(self, other):
554 if isinstance(other, UserList):
555 return self.__class__(other.data + self.data)
556 elif isinstance(other, type(self.data)):
557 return self.__class__(other + self.data)
558 return self.__class__(list(other) + self.data)
559 def __iadd__(self, other):
560 if isinstance(other, UserList):
561 self.data += other.data
562 elif isinstance(other, type(self.data)):
563 self.data += other
564 else:
565 self.data += list(other)
566 return self
567 def __mul__(self, n):
568 return self.__class__(self.data*n)
569 __rmul__ = __mul__
570 def __imul__(self, n):
571 self.data *= n
572 return self
573 def append(self, item): self.data.append(item)
574 def insert(self, i, item): self.data.insert(i, item)
575 def pop(self, i=-1): return self.data.pop(i)
576 def remove(self, item): self.data.remove(item)
577 def count(self, item): return self.data.count(item)
578 def index(self, item, *args): return self.data.index(item, *args)
579 def reverse(self): self.data.reverse()
580 def sort(self, *args, **kwds): self.data.sort(*args, **kwds)
581 def extend(self, other):
582 if isinstance(other, UserList):
583 self.data.extend(other.data)
584 else:
585 self.data.extend(other)
586
587
588
589################################################################################
Raymond Hettingerb3a65f82008-02-21 22:11:37 +0000590### UserString
591################################################################################
592
593class UserString(Sequence):
594 def __init__(self, seq):
595 if isinstance(seq, str):
596 self.data = seq
597 elif isinstance(seq, UserString):
598 self.data = seq.data[:]
599 else:
600 self.data = str(seq)
601 def __str__(self): return str(self.data)
602 def __repr__(self): return repr(self.data)
603 def __int__(self): return int(self.data)
Raymond Hettingerb3a65f82008-02-21 22:11:37 +0000604 def __float__(self): return float(self.data)
605 def __complex__(self): return complex(self.data)
606 def __hash__(self): return hash(self.data)
607
608 def __eq__(self, string):
609 if isinstance(string, UserString):
610 return self.data == string.data
611 return self.data == string
612 def __ne__(self, string):
613 if isinstance(string, UserString):
614 return self.data != string.data
615 return self.data != string
616 def __lt__(self, string):
617 if isinstance(string, UserString):
618 return self.data < string.data
619 return self.data < string
620 def __le__(self, string):
621 if isinstance(string, UserString):
622 return self.data <= string.data
623 return self.data <= string
624 def __gt__(self, string):
625 if isinstance(string, UserString):
626 return self.data > string.data
627 return self.data > string
628 def __ge__(self, string):
629 if isinstance(string, UserString):
630 return self.data >= string.data
631 return self.data >= string
632
633 def __contains__(self, char):
634 if isinstance(char, UserString):
635 char = char.data
636 return char in self.data
637
638 def __len__(self): return len(self.data)
639 def __getitem__(self, index): return self.__class__(self.data[index])
640 def __add__(self, other):
641 if isinstance(other, UserString):
642 return self.__class__(self.data + other.data)
643 elif isinstance(other, str):
644 return self.__class__(self.data + other)
645 return self.__class__(self.data + str(other))
646 def __radd__(self, other):
647 if isinstance(other, str):
648 return self.__class__(other + self.data)
649 return self.__class__(str(other) + self.data)
650 def __mul__(self, n):
651 return self.__class__(self.data*n)
652 __rmul__ = __mul__
653 def __mod__(self, args):
654 return self.__class__(self.data % args)
655
656 # the following methods are defined in alphabetical order:
657 def capitalize(self): return self.__class__(self.data.capitalize())
658 def center(self, width, *args):
659 return self.__class__(self.data.center(width, *args))
660 def count(self, sub, start=0, end=_sys.maxsize):
661 if isinstance(sub, UserString):
662 sub = sub.data
663 return self.data.count(sub, start, end)
664 def encode(self, encoding=None, errors=None): # XXX improve this?
665 if encoding:
666 if errors:
667 return self.__class__(self.data.encode(encoding, errors))
668 return self.__class__(self.data.encode(encoding))
669 return self.__class__(self.data.encode())
670 def endswith(self, suffix, start=0, end=_sys.maxsize):
671 return self.data.endswith(suffix, start, end)
672 def expandtabs(self, tabsize=8):
673 return self.__class__(self.data.expandtabs(tabsize))
674 def find(self, sub, start=0, end=_sys.maxsize):
675 if isinstance(sub, UserString):
676 sub = sub.data
677 return self.data.find(sub, start, end)
678 def format(self, *args, **kwds):
679 return self.data.format(*args, **kwds)
680 def index(self, sub, start=0, end=_sys.maxsize):
681 return self.data.index(sub, start, end)
682 def isalpha(self): return self.data.isalpha()
683 def isalnum(self): return self.data.isalnum()
684 def isdecimal(self): return self.data.isdecimal()
685 def isdigit(self): return self.data.isdigit()
686 def isidentifier(self): return self.data.isidentifier()
687 def islower(self): return self.data.islower()
688 def isnumeric(self): return self.data.isnumeric()
689 def isspace(self): return self.data.isspace()
690 def istitle(self): return self.data.istitle()
691 def isupper(self): return self.data.isupper()
692 def join(self, seq): return self.data.join(seq)
693 def ljust(self, width, *args):
694 return self.__class__(self.data.ljust(width, *args))
695 def lower(self): return self.__class__(self.data.lower())
696 def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars))
697 def partition(self, sep):
698 return self.data.partition(sep)
699 def replace(self, old, new, maxsplit=-1):
700 if isinstance(old, UserString):
701 old = old.data
702 if isinstance(new, UserString):
703 new = new.data
704 return self.__class__(self.data.replace(old, new, maxsplit))
705 def rfind(self, sub, start=0, end=_sys.maxsize):
706 return self.data.rfind(sub, start, end)
707 def rindex(self, sub, start=0, end=_sys.maxsize):
708 return self.data.rindex(sub, start, end)
709 def rjust(self, width, *args):
710 return self.__class__(self.data.rjust(width, *args))
711 def rpartition(self, sep):
712 return self.data.rpartition(sep)
713 def rstrip(self, chars=None):
714 return self.__class__(self.data.rstrip(chars))
715 def split(self, sep=None, maxsplit=-1):
716 return self.data.split(sep, maxsplit)
717 def rsplit(self, sep=None, maxsplit=-1):
718 return self.data.rsplit(sep, maxsplit)
719 def splitlines(self, keepends=0): return self.data.splitlines(keepends)
720 def startswith(self, prefix, start=0, end=_sys.maxsize):
721 return self.data.startswith(prefix, start, end)
722 def strip(self, chars=None): return self.__class__(self.data.strip(chars))
723 def swapcase(self): return self.__class__(self.data.swapcase())
724 def title(self): return self.__class__(self.data.title())
725 def translate(self, *args):
726 return self.__class__(self.data.translate(*args))
727 def upper(self): return self.__class__(self.data.upper())
728 def zfill(self, width): return self.__class__(self.data.zfill(width))
729
730
731
732################################################################################
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000733### Simple tests
734################################################################################
Guido van Rossumd8faa362007-04-27 19:54:29 +0000735
736if __name__ == '__main__':
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000737 # verify that instances can be pickled
Guido van Rossum99603b02007-07-20 00:22:32 +0000738 from pickle import loads, dumps
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000739 Point = namedtuple('Point', 'x, y', True)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000740 p = Point(x=10, y=20)
741 assert p == loads(dumps(p))
742
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000743 # test and demonstrate ability to override methods
Christian Heimes043d6f62008-01-07 17:19:16 +0000744 class Point(namedtuple('Point', 'x y')):
Christian Heimes25bb7832008-01-11 16:17:00 +0000745 __slots__ = ()
Christian Heimes043d6f62008-01-07 17:19:16 +0000746 @property
747 def hypot(self):
748 return (self.x ** 2 + self.y ** 2) ** 0.5
Christian Heimes790c8232008-01-07 21:14:23 +0000749 def __str__(self):
Christian Heimes25bb7832008-01-11 16:17:00 +0000750 return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot)
Christian Heimes043d6f62008-01-07 17:19:16 +0000751
Christian Heimes25bb7832008-01-11 16:17:00 +0000752 for p in Point(3, 4), Point(14, 5/7.):
Christian Heimes790c8232008-01-07 21:14:23 +0000753 print (p)
Christian Heimes043d6f62008-01-07 17:19:16 +0000754
755 class Point(namedtuple('Point', 'x y')):
756 'Point class with optimized _make() and _replace() without error-checking'
Christian Heimes25bb7832008-01-11 16:17:00 +0000757 __slots__ = ()
Christian Heimes043d6f62008-01-07 17:19:16 +0000758 _make = classmethod(tuple.__new__)
759 def _replace(self, _map=map, **kwds):
Christian Heimes2380ac72008-01-09 00:17:24 +0000760 return self._make(_map(kwds.get, ('x', 'y'), self))
Christian Heimes043d6f62008-01-07 17:19:16 +0000761
762 print(Point(11, 22)._replace(x=100))
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000763
Christian Heimes25bb7832008-01-11 16:17:00 +0000764 Point3D = namedtuple('Point3D', Point._fields + ('z',))
765 print(Point3D.__doc__)
766
Guido van Rossumd8faa362007-04-27 19:54:29 +0000767 import doctest
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000768 TestResults = namedtuple('TestResults', 'failed attempted')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000769 print(TestResults(*doctest.testmod()))