blob: a1e8ed975bf8de104a8b392f7e252423c803cec5 [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:
26 self.__keys
27 except AttributeError:
28 # Note the underlying data structure for this class is likely to
29 # change in the future. Do not rely on it or access it directly.
30 self.__keys = []
Raymond Hettinger2d32f632009-03-02 21:24:57 +000031 self.update(*args, **kwds)
32
33 def clear(self):
Raymond Hettinger08c70cf2009-03-03 20:47:29 +000034 del self.__keys[:]
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 Hettinger08c70cf2009-03-03 20:47:29 +000039 self.__keys.append(key)
Raymond Hettinger2d32f632009-03-02 21:24:57 +000040 dict.__setitem__(self, key, value)
41
42 def __delitem__(self, key):
43 dict.__delitem__(self, key)
Raymond Hettinger08c70cf2009-03-03 20:47:29 +000044 self.__keys.remove(key)
Raymond Hettinger2d32f632009-03-02 21:24:57 +000045
46 def __iter__(self):
Raymond Hettinger08c70cf2009-03-03 20:47:29 +000047 return iter(self.__keys)
Raymond Hettinger2d32f632009-03-02 21:24:57 +000048
49 def __reversed__(self):
Raymond Hettinger08c70cf2009-03-03 20:47:29 +000050 return reversed(self.__keys)
Raymond Hettinger2d32f632009-03-02 21:24:57 +000051
52 def popitem(self):
53 if not self:
54 raise KeyError('dictionary is empty')
Raymond Hettinger08c70cf2009-03-03 20:47:29 +000055 key = self.__keys.pop()
Raymond Hettinger2d32f632009-03-02 21:24:57 +000056 value = dict.pop(self, key)
57 return key, value
58
59 def __reduce__(self):
60 items = [[k, self[k]] for k in self]
Raymond Hettinger14b89ff2009-03-03 22:20:56 +000061 tmp = self.__keys
62 del self.__keys
Raymond Hettinger2d32f632009-03-02 21:24:57 +000063 inst_dict = vars(self).copy()
Raymond Hettinger14b89ff2009-03-03 22:20:56 +000064 self.__keys = tmp
65 if inst_dict:
66 return (self.__class__, (items,), inst_dict)
67 return self.__class__, (items,)
Raymond Hettinger2d32f632009-03-02 21:24:57 +000068
69 setdefault = MutableMapping.setdefault
70 update = MutableMapping.update
71 pop = MutableMapping.pop
72 keys = MutableMapping.keys
73 values = MutableMapping.values
74 items = MutableMapping.items
75
76 def __repr__(self):
77 if not self:
78 return '%s()' % (self.__class__.__name__,)
79 return '%s(%r)' % (self.__class__.__name__, list(self.items()))
80
81 def copy(self):
82 return self.__class__(self)
83
84 @classmethod
85 def fromkeys(cls, iterable, value=None):
86 d = cls()
87 for key in iterable:
88 d[key] = value
89 return d
90
91 def __eq__(self, other):
92 if isinstance(other, OrderedDict):
Raymond Hettingerea9f8db2009-03-02 21:28:41 +000093 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 +000094 return dict.__eq__(self, other)
95
Raymond Hettingerb8baf632009-01-14 02:20:07 +000096
Christian Heimes99170a52007-12-19 02:07:34 +000097
Raymond Hettinger48b8b662008-02-05 01:53:00 +000098################################################################################
99### namedtuple
100################################################################################
101
Benjamin Petersona86f2c02009-02-10 02:41:10 +0000102def namedtuple(typename, field_names, verbose=False, rename=False):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000103 """Returns a new subclass of tuple with named fields.
104
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000105 >>> Point = namedtuple('Point', 'x y')
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000106 >>> Point.__doc__ # docstring for the new class
Guido van Rossumd8faa362007-04-27 19:54:29 +0000107 'Point(x, y)'
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000108 >>> p = Point(11, y=22) # instantiate with positional args or keywords
Christian Heimes99170a52007-12-19 02:07:34 +0000109 >>> p[0] + p[1] # indexable like a plain tuple
Guido van Rossumd8faa362007-04-27 19:54:29 +0000110 33
Christian Heimes99170a52007-12-19 02:07:34 +0000111 >>> x, y = p # unpack like a regular tuple
Guido van Rossumd8faa362007-04-27 19:54:29 +0000112 >>> x, y
113 (11, 22)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000114 >>> p.x + p.y # fields also accessable by name
Guido van Rossumd8faa362007-04-27 19:54:29 +0000115 33
Christian Heimes0449f632007-12-15 01:27:15 +0000116 >>> d = p._asdict() # convert to a dictionary
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000117 >>> d['x']
118 11
119 >>> Point(**d) # convert from a dictionary
Guido van Rossumd8faa362007-04-27 19:54:29 +0000120 Point(x=11, y=22)
Christian Heimes0449f632007-12-15 01:27:15 +0000121 >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000122 Point(x=100, y=22)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000123
124 """
125
Christian Heimes2380ac72008-01-09 00:17:24 +0000126 # Parse and validate the field names. Validation serves two purposes,
127 # generating informative error messages and preventing template injection attacks.
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000128 if isinstance(field_names, str):
129 field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +0000130 field_names = tuple(map(str, field_names))
Benjamin Petersona86f2c02009-02-10 02:41:10 +0000131 if rename:
132 names = list(field_names)
133 seen = set()
134 for i, name in enumerate(names):
135 if (not all(c.isalnum() or c=='_' for c in name) or _iskeyword(name)
136 or not name or name[0].isdigit() or name.startswith('_')
137 or name in seen):
138 names[i] = '_%d' % (i+1)
139 seen.add(name)
140 field_names = tuple(names)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000141 for name in (typename,) + field_names:
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000142 if not all(c.isalnum() or c=='_' for c in name):
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000143 raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
144 if _iskeyword(name):
145 raise ValueError('Type names and field names cannot be a keyword: %r' % name)
146 if name[0].isdigit():
147 raise ValueError('Type names and field names cannot start with a number: %r' % name)
148 seen_names = set()
149 for name in field_names:
Benjamin Petersona86f2c02009-02-10 02:41:10 +0000150 if name.startswith('_') and not rename:
Christian Heimes0449f632007-12-15 01:27:15 +0000151 raise ValueError('Field names cannot start with an underscore: %r' % name)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000152 if name in seen_names:
153 raise ValueError('Encountered duplicate field name: %r' % name)
154 seen_names.add(name)
155
156 # Create and fill-in the class template
Christian Heimesfaf2f632008-01-06 16:59:19 +0000157 numfields = len(field_names)
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000158 argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000159 reprtxt = ', '.join('%s=%%r' % name for name in field_names)
160 template = '''class %(typename)s(tuple):
Christian Heimes0449f632007-12-15 01:27:15 +0000161 '%(typename)s(%(argtxt)s)' \n
162 __slots__ = () \n
Christian Heimesfaf2f632008-01-06 16:59:19 +0000163 _fields = %(field_names)r \n
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000164 def __new__(cls, %(argtxt)s):
Christian Heimes0449f632007-12-15 01:27:15 +0000165 return tuple.__new__(cls, (%(argtxt)s)) \n
Christian Heimesfaf2f632008-01-06 16:59:19 +0000166 @classmethod
Christian Heimes043d6f62008-01-07 17:19:16 +0000167 def _make(cls, iterable, new=tuple.__new__, len=len):
Christian Heimesfaf2f632008-01-06 16:59:19 +0000168 'Make a new %(typename)s object from a sequence or iterable'
Christian Heimes043d6f62008-01-07 17:19:16 +0000169 result = new(cls, iterable)
Christian Heimesfaf2f632008-01-06 16:59:19 +0000170 if len(result) != %(numfields)d:
171 raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
172 return result \n
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000173 def __repr__(self):
Christian Heimes0449f632007-12-15 01:27:15 +0000174 return '%(typename)s(%(reprtxt)s)' %% self \n
Raymond Hettingera4f52b12009-03-02 22:28:31 +0000175 def _asdict(self):
176 'Return a new OrderedDict which maps field names to their values'
177 return OrderedDict(zip(self._fields, self)) \n
Christian Heimes0449f632007-12-15 01:27:15 +0000178 def _replace(self, **kwds):
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000179 'Return a new %(typename)s object replacing specified fields with new values'
Christian Heimesfaf2f632008-01-06 16:59:19 +0000180 result = self._make(map(kwds.pop, %(field_names)r, self))
181 if kwds:
182 raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000183 return result \n
184 def __getnewargs__(self):
185 return tuple(self) \n\n''' % locals()
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000186 for i, name in enumerate(field_names):
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000187 template += ' %s = property(itemgetter(%d))\n' % (name, i)
188 if verbose:
189 print(template)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000190
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000191 # Execute the template string in a temporary namespace and
192 # support tracing utilities by setting a value for frame.f_globals['__name__']
Raymond Hettingera4f52b12009-03-02 22:28:31 +0000193 namespace = dict(itemgetter=_itemgetter, __name__='namedtuple_%s' % typename,
194 OrderedDict=OrderedDict)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000195 try:
196 exec(template, namespace)
197 except SyntaxError as e:
Christian Heimes99170a52007-12-19 02:07:34 +0000198 raise SyntaxError(e.msg + ':\n' + template) from e
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000199 result = namespace[typename]
200
201 # For pickling to work, the __module__ variable needs to be set to the frame
202 # where the named tuple is created. Bypass this step in enviroments where
203 # sys._getframe is not defined (Jython for example).
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000204 if hasattr(_sys, '_getframe'):
Raymond Hettinger0f055172009-01-27 10:06:09 +0000205 result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__')
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000206
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000207 return result
Guido van Rossumd8faa362007-04-27 19:54:29 +0000208
Guido van Rossumd8faa362007-04-27 19:54:29 +0000209
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000210########################################################################
211### Counter
212########################################################################
213
214class Counter(dict):
215 '''Dict subclass for counting hashable items. Sometimes called a bag
216 or multiset. Elements are stored as dictionary keys and their counts
217 are stored as dictionary values.
218
219 >>> c = Counter('abracadabra') # count elements from a string
220
221 >>> c.most_common(3) # three most common elements
222 [('a', 5), ('r', 2), ('b', 2)]
223 >>> sorted(c) # list all unique elements
224 ['a', 'b', 'c', 'd', 'r']
225 >>> ''.join(sorted(c.elements())) # list elements with repetitions
226 'aaaaabbcdrr'
227 >>> sum(c.values()) # total of all counts
228 11
229
230 >>> c['a'] # count of letter 'a'
231 5
232 >>> for elem in 'shazam': # update counts from an iterable
233 ... c[elem] += 1 # by adding 1 to each element's count
234 >>> c['a'] # now there are seven 'a'
235 7
236 >>> del c['r'] # remove all 'r'
237 >>> c['r'] # now there are zero 'r'
238 0
239
240 >>> d = Counter('simsalabim') # make another counter
241 >>> c.update(d) # add in the second counter
242 >>> c['a'] # now there are nine 'a'
243 9
244
245 >>> c.clear() # empty the counter
246 >>> c
247 Counter()
248
249 Note: If a count is set to zero or reduced to zero, it will remain
250 in the counter until the entry is deleted or the counter is cleared:
251
252 >>> c = Counter('aaabbc')
253 >>> c['b'] -= 2 # reduce the count of 'b' by two
254 >>> c.most_common() # 'b' is still in, but its count is zero
255 [('a', 3), ('c', 1), ('b', 0)]
256
257 '''
258 # References:
259 # http://en.wikipedia.org/wiki/Multiset
260 # http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html
261 # http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm
262 # http://code.activestate.com/recipes/259174/
263 # Knuth, TAOCP Vol. II section 4.6.3
264
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000265 def __init__(self, iterable=None, **kwds):
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000266 '''Create a new, empty Counter object. And if given, count elements
267 from an input iterable. Or, initialize the count from another mapping
268 of elements to their counts.
269
270 >>> c = Counter() # a new, empty counter
271 >>> c = Counter('gallahad') # a new counter from an iterable
272 >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000273 >>> c = Counter(a=4, b=2) # a new counter from keyword args
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000274
275 '''
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000276 self.update(iterable, **kwds)
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000277
278 def __missing__(self, key):
279 'The count of elements not in the Counter is zero.'
280 # Needed so that self[missing_item] does not raise KeyError
281 return 0
282
283 def most_common(self, n=None):
284 '''List the n most common elements and their counts from the most
285 common to the least. If n is None, then list all element counts.
286
287 >>> Counter('abracadabra').most_common(3)
288 [('a', 5), ('r', 2), ('b', 2)]
289
290 '''
291 # Emulate Bag.sortedByCount from Smalltalk
292 if n is None:
293 return sorted(self.items(), key=_itemgetter(1), reverse=True)
294 return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
295
296 def elements(self):
297 '''Iterator over elements repeating each as many times as its count.
298
299 >>> c = Counter('ABCABC')
300 >>> sorted(c.elements())
301 ['A', 'A', 'B', 'B', 'C', 'C']
302
303 # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1
304 >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
305 >>> product = 1
306 >>> for factor in prime_factors.elements(): # loop over factors
307 ... product *= factor # and multiply them
308 >>> product
309 1836
310
311 Note, if an element's count has been set to zero or is a negative
312 number, elements() will ignore it.
313
314 '''
315 # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
316 return _chain.from_iterable(_starmap(_repeat, self.items()))
317
318 # Override dict methods where necessary
319
320 @classmethod
321 def fromkeys(cls, iterable, v=None):
322 # There is no equivalent method for counters because setting v=1
323 # means that no element can have a count greater than one.
324 raise NotImplementedError(
325 'Counter.fromkeys() is undefined. Use Counter(iterable) instead.')
326
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000327 def update(self, iterable=None, **kwds):
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000328 '''Like dict.update() but add counts instead of replacing them.
329
330 Source can be an iterable, a dictionary, or another Counter instance.
331
332 >>> c = Counter('which')
333 >>> c.update('witch') # add elements from another iterable
334 >>> d = Counter('watch')
335 >>> c.update(d) # add elements from another counter
336 >>> c['h'] # four 'h' in which, witch, and watch
337 4
338
339 '''
340 # The regular dict.update() operation makes no sense here because the
341 # replace behavior results in the some of original untouched counts
342 # being mixed-in with all of the other counts for a mismash that
343 # doesn't have a straight-forward interpretation in most counting
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000344 # contexts. Instead, we implement straight-addition. Both the inputs
345 # and outputs are allowed to contain zero and negative counts.
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000346
347 if iterable is not None:
348 if isinstance(iterable, Mapping):
Raymond Hettingerdd01f8f2009-01-22 09:09:55 +0000349 if self:
350 for elem, count in iterable.items():
351 self[elem] += count
352 else:
353 dict.update(self, iterable) # fast path when counter is empty
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000354 else:
355 for elem in iterable:
356 self[elem] += 1
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000357 if kwds:
358 self.update(kwds)
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000359
360 def copy(self):
361 'Like dict.copy() but returns a Counter instance instead of a dict.'
362 return Counter(self)
363
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000364 def __delitem__(self, elem):
365 'Like dict.__delitem__() but does not raise KeyError for missing values.'
366 if elem in self:
367 dict.__delitem__(self, elem)
368
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000369 def __repr__(self):
370 if not self:
371 return '%s()' % self.__class__.__name__
372 items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
373 return '%s({%s})' % (self.__class__.__name__, items)
374
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000375 # Multiset-style mathematical operations discussed in:
376 # Knuth TAOCP Volume II section 4.6.3 exercise 19
377 # and at http://en.wikipedia.org/wiki/Multiset
378 #
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000379 # Outputs guaranteed to only include positive counts.
380 #
381 # To strip negative and zero counts, add-in an empty counter:
382 # c += Counter()
383
384 def __add__(self, other):
385 '''Add counts from two counters.
386
387 >>> Counter('abbb') + Counter('bcc')
388 Counter({'b': 4, 'c': 2, 'a': 1})
389
390 '''
391 if not isinstance(other, Counter):
392 return NotImplemented
393 result = Counter()
394 for elem in set(self) | set(other):
395 newcount = self[elem] + other[elem]
396 if newcount > 0:
397 result[elem] = newcount
398 return result
399
400 def __sub__(self, other):
401 ''' Subtract count, but keep only results with positive counts.
402
403 >>> Counter('abbbc') - Counter('bccd')
404 Counter({'b': 2, 'a': 1})
405
406 '''
407 if not isinstance(other, Counter):
408 return NotImplemented
409 result = Counter()
Raymond Hettingere0d1b9f2009-01-21 20:36:27 +0000410 for elem in set(self) | set(other):
411 newcount = self[elem] - other[elem]
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000412 if newcount > 0:
413 result[elem] = newcount
414 return result
415
416 def __or__(self, other):
417 '''Union is the maximum of value in either of the input counters.
418
419 >>> Counter('abbb') | Counter('bcc')
420 Counter({'b': 3, 'c': 2, 'a': 1})
421
422 '''
423 if not isinstance(other, Counter):
424 return NotImplemented
425 _max = max
426 result = Counter()
427 for elem in set(self) | set(other):
428 newcount = _max(self[elem], other[elem])
429 if newcount > 0:
430 result[elem] = newcount
431 return result
432
433 def __and__(self, other):
434 ''' Intersection is the minimum of corresponding counts.
435
436 >>> Counter('abbb') & Counter('bcc')
437 Counter({'b': 1})
438
439 '''
440 if not isinstance(other, Counter):
441 return NotImplemented
442 _min = min
443 result = Counter()
444 if len(self) < len(other):
445 self, other = other, self
446 for elem in filter(self.__contains__, other):
447 newcount = _min(self[elem], other[elem])
448 if newcount > 0:
449 result[elem] = newcount
450 return result
451
Guido van Rossumd8faa362007-04-27 19:54:29 +0000452
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000453################################################################################
454### UserDict
455################################################################################
Guido van Rossumd8faa362007-04-27 19:54:29 +0000456
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000457class UserDict(MutableMapping):
458
459 # Start by filling-out the abstract methods
460 def __init__(self, dict=None, **kwargs):
461 self.data = {}
462 if dict is not None:
463 self.update(dict)
464 if len(kwargs):
465 self.update(kwargs)
466 def __len__(self): return len(self.data)
467 def __getitem__(self, key):
468 if key in self.data:
469 return self.data[key]
470 if hasattr(self.__class__, "__missing__"):
471 return self.__class__.__missing__(self, key)
472 raise KeyError(key)
473 def __setitem__(self, key, item): self.data[key] = item
474 def __delitem__(self, key): del self.data[key]
475 def __iter__(self):
476 return iter(self.data)
477
Raymond Hettinger554c8b82008-02-05 22:54:43 +0000478 # Modify __contains__ to work correctly when __missing__ is present
479 def __contains__(self, key):
480 return key in self.data
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000481
482 # Now, add the methods in dicts but not in MutableMapping
483 def __repr__(self): return repr(self.data)
484 def copy(self):
485 if self.__class__ is UserDict:
486 return UserDict(self.data.copy())
487 import copy
488 data = self.data
489 try:
490 self.data = {}
491 c = copy.copy(self)
492 finally:
493 self.data = data
494 c.update(self)
495 return c
496 @classmethod
497 def fromkeys(cls, iterable, value=None):
498 d = cls()
499 for key in iterable:
500 d[key] = value
501 return d
502
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000503
504
505################################################################################
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000506### UserList
507################################################################################
508
509class UserList(MutableSequence):
510 """A more or less complete user-defined wrapper around list objects."""
511 def __init__(self, initlist=None):
512 self.data = []
513 if initlist is not None:
514 # XXX should this accept an arbitrary sequence?
515 if type(initlist) == type(self.data):
516 self.data[:] = initlist
517 elif isinstance(initlist, UserList):
518 self.data[:] = initlist.data[:]
519 else:
520 self.data = list(initlist)
521 def __repr__(self): return repr(self.data)
522 def __lt__(self, other): return self.data < self.__cast(other)
523 def __le__(self, other): return self.data <= self.__cast(other)
524 def __eq__(self, other): return self.data == self.__cast(other)
525 def __ne__(self, other): return self.data != self.__cast(other)
526 def __gt__(self, other): return self.data > self.__cast(other)
527 def __ge__(self, other): return self.data >= self.__cast(other)
528 def __cast(self, other):
529 return other.data if isinstance(other, UserList) else other
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000530 def __contains__(self, item): return item in self.data
531 def __len__(self): return len(self.data)
532 def __getitem__(self, i): return self.data[i]
533 def __setitem__(self, i, item): self.data[i] = item
534 def __delitem__(self, i): del self.data[i]
535 def __add__(self, other):
536 if isinstance(other, UserList):
537 return self.__class__(self.data + other.data)
538 elif isinstance(other, type(self.data)):
539 return self.__class__(self.data + other)
540 return self.__class__(self.data + list(other))
541 def __radd__(self, other):
542 if isinstance(other, UserList):
543 return self.__class__(other.data + self.data)
544 elif isinstance(other, type(self.data)):
545 return self.__class__(other + self.data)
546 return self.__class__(list(other) + self.data)
547 def __iadd__(self, other):
548 if isinstance(other, UserList):
549 self.data += other.data
550 elif isinstance(other, type(self.data)):
551 self.data += other
552 else:
553 self.data += list(other)
554 return self
555 def __mul__(self, n):
556 return self.__class__(self.data*n)
557 __rmul__ = __mul__
558 def __imul__(self, n):
559 self.data *= n
560 return self
561 def append(self, item): self.data.append(item)
562 def insert(self, i, item): self.data.insert(i, item)
563 def pop(self, i=-1): return self.data.pop(i)
564 def remove(self, item): self.data.remove(item)
565 def count(self, item): return self.data.count(item)
566 def index(self, item, *args): return self.data.index(item, *args)
567 def reverse(self): self.data.reverse()
568 def sort(self, *args, **kwds): self.data.sort(*args, **kwds)
569 def extend(self, other):
570 if isinstance(other, UserList):
571 self.data.extend(other.data)
572 else:
573 self.data.extend(other)
574
575
576
577################################################################################
Raymond Hettingerb3a65f82008-02-21 22:11:37 +0000578### UserString
579################################################################################
580
581class UserString(Sequence):
582 def __init__(self, seq):
583 if isinstance(seq, str):
584 self.data = seq
585 elif isinstance(seq, UserString):
586 self.data = seq.data[:]
587 else:
588 self.data = str(seq)
589 def __str__(self): return str(self.data)
590 def __repr__(self): return repr(self.data)
591 def __int__(self): return int(self.data)
Raymond Hettingerb3a65f82008-02-21 22:11:37 +0000592 def __float__(self): return float(self.data)
593 def __complex__(self): return complex(self.data)
594 def __hash__(self): return hash(self.data)
595
596 def __eq__(self, string):
597 if isinstance(string, UserString):
598 return self.data == string.data
599 return self.data == string
600 def __ne__(self, string):
601 if isinstance(string, UserString):
602 return self.data != string.data
603 return self.data != string
604 def __lt__(self, string):
605 if isinstance(string, UserString):
606 return self.data < string.data
607 return self.data < string
608 def __le__(self, string):
609 if isinstance(string, UserString):
610 return self.data <= string.data
611 return self.data <= string
612 def __gt__(self, string):
613 if isinstance(string, UserString):
614 return self.data > string.data
615 return self.data > string
616 def __ge__(self, string):
617 if isinstance(string, UserString):
618 return self.data >= string.data
619 return self.data >= string
620
621 def __contains__(self, char):
622 if isinstance(char, UserString):
623 char = char.data
624 return char in self.data
625
626 def __len__(self): return len(self.data)
627 def __getitem__(self, index): return self.__class__(self.data[index])
628 def __add__(self, other):
629 if isinstance(other, UserString):
630 return self.__class__(self.data + other.data)
631 elif isinstance(other, str):
632 return self.__class__(self.data + other)
633 return self.__class__(self.data + str(other))
634 def __radd__(self, other):
635 if isinstance(other, str):
636 return self.__class__(other + self.data)
637 return self.__class__(str(other) + self.data)
638 def __mul__(self, n):
639 return self.__class__(self.data*n)
640 __rmul__ = __mul__
641 def __mod__(self, args):
642 return self.__class__(self.data % args)
643
644 # the following methods are defined in alphabetical order:
645 def capitalize(self): return self.__class__(self.data.capitalize())
646 def center(self, width, *args):
647 return self.__class__(self.data.center(width, *args))
648 def count(self, sub, start=0, end=_sys.maxsize):
649 if isinstance(sub, UserString):
650 sub = sub.data
651 return self.data.count(sub, start, end)
652 def encode(self, encoding=None, errors=None): # XXX improve this?
653 if encoding:
654 if errors:
655 return self.__class__(self.data.encode(encoding, errors))
656 return self.__class__(self.data.encode(encoding))
657 return self.__class__(self.data.encode())
658 def endswith(self, suffix, start=0, end=_sys.maxsize):
659 return self.data.endswith(suffix, start, end)
660 def expandtabs(self, tabsize=8):
661 return self.__class__(self.data.expandtabs(tabsize))
662 def find(self, sub, start=0, end=_sys.maxsize):
663 if isinstance(sub, UserString):
664 sub = sub.data
665 return self.data.find(sub, start, end)
666 def format(self, *args, **kwds):
667 return self.data.format(*args, **kwds)
668 def index(self, sub, start=0, end=_sys.maxsize):
669 return self.data.index(sub, start, end)
670 def isalpha(self): return self.data.isalpha()
671 def isalnum(self): return self.data.isalnum()
672 def isdecimal(self): return self.data.isdecimal()
673 def isdigit(self): return self.data.isdigit()
674 def isidentifier(self): return self.data.isidentifier()
675 def islower(self): return self.data.islower()
676 def isnumeric(self): return self.data.isnumeric()
677 def isspace(self): return self.data.isspace()
678 def istitle(self): return self.data.istitle()
679 def isupper(self): return self.data.isupper()
680 def join(self, seq): return self.data.join(seq)
681 def ljust(self, width, *args):
682 return self.__class__(self.data.ljust(width, *args))
683 def lower(self): return self.__class__(self.data.lower())
684 def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars))
685 def partition(self, sep):
686 return self.data.partition(sep)
687 def replace(self, old, new, maxsplit=-1):
688 if isinstance(old, UserString):
689 old = old.data
690 if isinstance(new, UserString):
691 new = new.data
692 return self.__class__(self.data.replace(old, new, maxsplit))
693 def rfind(self, sub, start=0, end=_sys.maxsize):
694 return self.data.rfind(sub, start, end)
695 def rindex(self, sub, start=0, end=_sys.maxsize):
696 return self.data.rindex(sub, start, end)
697 def rjust(self, width, *args):
698 return self.__class__(self.data.rjust(width, *args))
699 def rpartition(self, sep):
700 return self.data.rpartition(sep)
701 def rstrip(self, chars=None):
702 return self.__class__(self.data.rstrip(chars))
703 def split(self, sep=None, maxsplit=-1):
704 return self.data.split(sep, maxsplit)
705 def rsplit(self, sep=None, maxsplit=-1):
706 return self.data.rsplit(sep, maxsplit)
707 def splitlines(self, keepends=0): return self.data.splitlines(keepends)
708 def startswith(self, prefix, start=0, end=_sys.maxsize):
709 return self.data.startswith(prefix, start, end)
710 def strip(self, chars=None): return self.__class__(self.data.strip(chars))
711 def swapcase(self): return self.__class__(self.data.swapcase())
712 def title(self): return self.__class__(self.data.title())
713 def translate(self, *args):
714 return self.__class__(self.data.translate(*args))
715 def upper(self): return self.__class__(self.data.upper())
716 def zfill(self, width): return self.__class__(self.data.zfill(width))
717
718
719
720################################################################################
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000721### Simple tests
722################################################################################
Guido van Rossumd8faa362007-04-27 19:54:29 +0000723
724if __name__ == '__main__':
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000725 # verify that instances can be pickled
Guido van Rossum99603b02007-07-20 00:22:32 +0000726 from pickle import loads, dumps
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000727 Point = namedtuple('Point', 'x, y', True)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000728 p = Point(x=10, y=20)
729 assert p == loads(dumps(p))
730
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000731 # test and demonstrate ability to override methods
Christian Heimes043d6f62008-01-07 17:19:16 +0000732 class Point(namedtuple('Point', 'x y')):
Christian Heimes25bb7832008-01-11 16:17:00 +0000733 __slots__ = ()
Christian Heimes043d6f62008-01-07 17:19:16 +0000734 @property
735 def hypot(self):
736 return (self.x ** 2 + self.y ** 2) ** 0.5
Christian Heimes790c8232008-01-07 21:14:23 +0000737 def __str__(self):
Christian Heimes25bb7832008-01-11 16:17:00 +0000738 return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot)
Christian Heimes043d6f62008-01-07 17:19:16 +0000739
Christian Heimes25bb7832008-01-11 16:17:00 +0000740 for p in Point(3, 4), Point(14, 5/7.):
Christian Heimes790c8232008-01-07 21:14:23 +0000741 print (p)
Christian Heimes043d6f62008-01-07 17:19:16 +0000742
743 class Point(namedtuple('Point', 'x y')):
744 'Point class with optimized _make() and _replace() without error-checking'
Christian Heimes25bb7832008-01-11 16:17:00 +0000745 __slots__ = ()
Christian Heimes043d6f62008-01-07 17:19:16 +0000746 _make = classmethod(tuple.__new__)
747 def _replace(self, _map=map, **kwds):
Christian Heimes2380ac72008-01-09 00:17:24 +0000748 return self._make(_map(kwds.get, ('x', 'y'), self))
Christian Heimes043d6f62008-01-07 17:19:16 +0000749
750 print(Point(11, 22)._replace(x=100))
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000751
Christian Heimes25bb7832008-01-11 16:17:00 +0000752 Point3D = namedtuple('Point3D', Point._fields + ('z',))
753 print(Point3D.__doc__)
754
Guido van Rossumd8faa362007-04-27 19:54:29 +0000755 import doctest
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000756 TestResults = namedtuple('TestResults', 'failed attempted')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000757 print(TestResults(*doctest.testmod()))