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