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