blob: 4bde5b36b7c7c5f27b419122fc015b9639c13800 [file] [log] [blame]
Brett Cannon23a4a7b2008-05-12 00:56:28 +00001__all__ = ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList',
Raymond Hettinger4d2073a2009-01-20 03:41:22 +00002 'UserString', 'Counter']
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
14from itertools import repeat as _repeat, chain as _chain, starmap as _starmap
15
Christian Heimes99170a52007-12-19 02:07:34 +000016
Raymond Hettinger48b8b662008-02-05 01:53:00 +000017################################################################################
18### namedtuple
19################################################################################
20
Guido van Rossum8ce8a782007-11-01 19:42:39 +000021def namedtuple(typename, field_names, verbose=False):
Guido van Rossumd8faa362007-04-27 19:54:29 +000022 """Returns a new subclass of tuple with named fields.
23
Guido van Rossum8ce8a782007-11-01 19:42:39 +000024 >>> Point = namedtuple('Point', 'x y')
Thomas Wouters1b7f8912007-09-19 03:06:30 +000025 >>> Point.__doc__ # docstring for the new class
Guido van Rossumd8faa362007-04-27 19:54:29 +000026 'Point(x, y)'
Thomas Wouters1b7f8912007-09-19 03:06:30 +000027 >>> p = Point(11, y=22) # instantiate with positional args or keywords
Christian Heimes99170a52007-12-19 02:07:34 +000028 >>> p[0] + p[1] # indexable like a plain tuple
Guido van Rossumd8faa362007-04-27 19:54:29 +000029 33
Christian Heimes99170a52007-12-19 02:07:34 +000030 >>> x, y = p # unpack like a regular tuple
Guido van Rossumd8faa362007-04-27 19:54:29 +000031 >>> x, y
32 (11, 22)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000033 >>> p.x + p.y # fields also accessable by name
Guido van Rossumd8faa362007-04-27 19:54:29 +000034 33
Christian Heimes0449f632007-12-15 01:27:15 +000035 >>> d = p._asdict() # convert to a dictionary
Guido van Rossum8ce8a782007-11-01 19:42:39 +000036 >>> d['x']
37 11
38 >>> Point(**d) # convert from a dictionary
Guido van Rossumd8faa362007-04-27 19:54:29 +000039 Point(x=11, y=22)
Christian Heimes0449f632007-12-15 01:27:15 +000040 >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Thomas Wouters1b7f8912007-09-19 03:06:30 +000041 Point(x=100, y=22)
Guido van Rossumd8faa362007-04-27 19:54:29 +000042
43 """
44
Christian Heimes2380ac72008-01-09 00:17:24 +000045 # Parse and validate the field names. Validation serves two purposes,
46 # generating informative error messages and preventing template injection attacks.
Guido van Rossum8ce8a782007-11-01 19:42:39 +000047 if isinstance(field_names, str):
48 field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +000049 field_names = tuple(map(str, field_names))
Guido van Rossum8ce8a782007-11-01 19:42:39 +000050 for name in (typename,) + field_names:
Christian Heimesb9eccbf2007-12-05 20:18:38 +000051 if not all(c.isalnum() or c=='_' for c in name):
Guido van Rossum8ce8a782007-11-01 19:42:39 +000052 raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
53 if _iskeyword(name):
54 raise ValueError('Type names and field names cannot be a keyword: %r' % name)
55 if name[0].isdigit():
56 raise ValueError('Type names and field names cannot start with a number: %r' % name)
57 seen_names = set()
58 for name in field_names:
Christian Heimes0449f632007-12-15 01:27:15 +000059 if name.startswith('_'):
60 raise ValueError('Field names cannot start with an underscore: %r' % name)
Guido van Rossum8ce8a782007-11-01 19:42:39 +000061 if name in seen_names:
62 raise ValueError('Encountered duplicate field name: %r' % name)
63 seen_names.add(name)
64
65 # Create and fill-in the class template
Christian Heimesfaf2f632008-01-06 16:59:19 +000066 numfields = len(field_names)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000067 argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes
Guido van Rossumd59da4b2007-05-22 18:11:13 +000068 reprtxt = ', '.join('%s=%%r' % name for name in field_names)
Christian Heimes99170a52007-12-19 02:07:34 +000069 dicttxt = ', '.join('%r: t[%d]' % (name, pos) for pos, name in enumerate(field_names))
Guido van Rossumd59da4b2007-05-22 18:11:13 +000070 template = '''class %(typename)s(tuple):
Christian Heimes0449f632007-12-15 01:27:15 +000071 '%(typename)s(%(argtxt)s)' \n
72 __slots__ = () \n
Christian Heimesfaf2f632008-01-06 16:59:19 +000073 _fields = %(field_names)r \n
Guido van Rossumd59da4b2007-05-22 18:11:13 +000074 def __new__(cls, %(argtxt)s):
Christian Heimes0449f632007-12-15 01:27:15 +000075 return tuple.__new__(cls, (%(argtxt)s)) \n
Christian Heimesfaf2f632008-01-06 16:59:19 +000076 @classmethod
Christian Heimes043d6f62008-01-07 17:19:16 +000077 def _make(cls, iterable, new=tuple.__new__, len=len):
Christian Heimesfaf2f632008-01-06 16:59:19 +000078 'Make a new %(typename)s object from a sequence or iterable'
Christian Heimes043d6f62008-01-07 17:19:16 +000079 result = new(cls, iterable)
Christian Heimesfaf2f632008-01-06 16:59:19 +000080 if len(result) != %(numfields)d:
81 raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
82 return result \n
Guido van Rossumd59da4b2007-05-22 18:11:13 +000083 def __repr__(self):
Christian Heimes0449f632007-12-15 01:27:15 +000084 return '%(typename)s(%(reprtxt)s)' %% self \n
Christian Heimes99170a52007-12-19 02:07:34 +000085 def _asdict(t):
Christian Heimes0449f632007-12-15 01:27:15 +000086 'Return a new dict which maps field names to their values'
Christian Heimes99170a52007-12-19 02:07:34 +000087 return {%(dicttxt)s} \n
Christian Heimes0449f632007-12-15 01:27:15 +000088 def _replace(self, **kwds):
Guido van Rossum3d392eb2007-11-16 00:35:22 +000089 'Return a new %(typename)s object replacing specified fields with new values'
Christian Heimesfaf2f632008-01-06 16:59:19 +000090 result = self._make(map(kwds.pop, %(field_names)r, self))
91 if kwds:
92 raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
Georg Brandlc28e1fa2008-06-10 19:20:26 +000093 return result \n
94 def __getnewargs__(self):
95 return tuple(self) \n\n''' % locals()
Guido van Rossumd59da4b2007-05-22 18:11:13 +000096 for i, name in enumerate(field_names):
Thomas Wouters1b7f8912007-09-19 03:06:30 +000097 template += ' %s = property(itemgetter(%d))\n' % (name, i)
98 if verbose:
99 print(template)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000100
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000101 # Execute the template string in a temporary namespace and
102 # support tracing utilities by setting a value for frame.f_globals['__name__']
103 namespace = dict(itemgetter=_itemgetter, __name__='namedtuple_%s' % typename)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000104 try:
105 exec(template, namespace)
106 except SyntaxError as e:
Christian Heimes99170a52007-12-19 02:07:34 +0000107 raise SyntaxError(e.msg + ':\n' + template) from e
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000108 result = namespace[typename]
109
110 # For pickling to work, the __module__ variable needs to be set to the frame
111 # where the named tuple is created. Bypass this step in enviroments where
112 # sys._getframe is not defined (Jython for example).
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000113 if hasattr(_sys, '_getframe'):
Raymond Hettinger0f055172009-01-27 10:06:09 +0000114 result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__')
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000115
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000116 return result
Guido van Rossumd8faa362007-04-27 19:54:29 +0000117
Guido van Rossumd8faa362007-04-27 19:54:29 +0000118
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000119########################################################################
120### Counter
121########################################################################
122
123class Counter(dict):
124 '''Dict subclass for counting hashable items. Sometimes called a bag
125 or multiset. Elements are stored as dictionary keys and their counts
126 are stored as dictionary values.
127
128 >>> c = Counter('abracadabra') # count elements from a string
129
130 >>> c.most_common(3) # three most common elements
131 [('a', 5), ('r', 2), ('b', 2)]
132 >>> sorted(c) # list all unique elements
133 ['a', 'b', 'c', 'd', 'r']
134 >>> ''.join(sorted(c.elements())) # list elements with repetitions
135 'aaaaabbcdrr'
136 >>> sum(c.values()) # total of all counts
137 11
138
139 >>> c['a'] # count of letter 'a'
140 5
141 >>> for elem in 'shazam': # update counts from an iterable
142 ... c[elem] += 1 # by adding 1 to each element's count
143 >>> c['a'] # now there are seven 'a'
144 7
145 >>> del c['r'] # remove all 'r'
146 >>> c['r'] # now there are zero 'r'
147 0
148
149 >>> d = Counter('simsalabim') # make another counter
150 >>> c.update(d) # add in the second counter
151 >>> c['a'] # now there are nine 'a'
152 9
153
154 >>> c.clear() # empty the counter
155 >>> c
156 Counter()
157
158 Note: If a count is set to zero or reduced to zero, it will remain
159 in the counter until the entry is deleted or the counter is cleared:
160
161 >>> c = Counter('aaabbc')
162 >>> c['b'] -= 2 # reduce the count of 'b' by two
163 >>> c.most_common() # 'b' is still in, but its count is zero
164 [('a', 3), ('c', 1), ('b', 0)]
165
166 '''
167 # References:
168 # http://en.wikipedia.org/wiki/Multiset
169 # http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html
170 # http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm
171 # http://code.activestate.com/recipes/259174/
172 # Knuth, TAOCP Vol. II section 4.6.3
173
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000174 def __init__(self, iterable=None, **kwds):
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000175 '''Create a new, empty Counter object. And if given, count elements
176 from an input iterable. Or, initialize the count from another mapping
177 of elements to their counts.
178
179 >>> c = Counter() # a new, empty counter
180 >>> c = Counter('gallahad') # a new counter from an iterable
181 >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000182 >>> c = Counter(a=4, b=2) # a new counter from keyword args
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000183
184 '''
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000185 self.update(iterable, **kwds)
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000186
187 def __missing__(self, key):
188 'The count of elements not in the Counter is zero.'
189 # Needed so that self[missing_item] does not raise KeyError
190 return 0
191
192 def most_common(self, n=None):
193 '''List the n most common elements and their counts from the most
194 common to the least. If n is None, then list all element counts.
195
196 >>> Counter('abracadabra').most_common(3)
197 [('a', 5), ('r', 2), ('b', 2)]
198
199 '''
200 # Emulate Bag.sortedByCount from Smalltalk
201 if n is None:
202 return sorted(self.items(), key=_itemgetter(1), reverse=True)
203 return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
204
205 def elements(self):
206 '''Iterator over elements repeating each as many times as its count.
207
208 >>> c = Counter('ABCABC')
209 >>> sorted(c.elements())
210 ['A', 'A', 'B', 'B', 'C', 'C']
211
212 # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1
213 >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
214 >>> product = 1
215 >>> for factor in prime_factors.elements(): # loop over factors
216 ... product *= factor # and multiply them
217 >>> product
218 1836
219
220 Note, if an element's count has been set to zero or is a negative
221 number, elements() will ignore it.
222
223 '''
224 # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
225 return _chain.from_iterable(_starmap(_repeat, self.items()))
226
227 # Override dict methods where necessary
228
229 @classmethod
230 def fromkeys(cls, iterable, v=None):
231 # There is no equivalent method for counters because setting v=1
232 # means that no element can have a count greater than one.
233 raise NotImplementedError(
234 'Counter.fromkeys() is undefined. Use Counter(iterable) instead.')
235
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000236 def update(self, iterable=None, **kwds):
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000237 '''Like dict.update() but add counts instead of replacing them.
238
239 Source can be an iterable, a dictionary, or another Counter instance.
240
241 >>> c = Counter('which')
242 >>> c.update('witch') # add elements from another iterable
243 >>> d = Counter('watch')
244 >>> c.update(d) # add elements from another counter
245 >>> c['h'] # four 'h' in which, witch, and watch
246 4
247
248 '''
249 # The regular dict.update() operation makes no sense here because the
250 # replace behavior results in the some of original untouched counts
251 # being mixed-in with all of the other counts for a mismash that
252 # doesn't have a straight-forward interpretation in most counting
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000253 # contexts. Instead, we implement straight-addition. Both the inputs
254 # and outputs are allowed to contain zero and negative counts.
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000255
256 if iterable is not None:
257 if isinstance(iterable, Mapping):
Raymond Hettingerdd01f8f2009-01-22 09:09:55 +0000258 if self:
259 for elem, count in iterable.items():
260 self[elem] += count
261 else:
262 dict.update(self, iterable) # fast path when counter is empty
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000263 else:
264 for elem in iterable:
265 self[elem] += 1
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000266 if kwds:
267 self.update(kwds)
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000268
269 def copy(self):
270 'Like dict.copy() but returns a Counter instance instead of a dict.'
271 return Counter(self)
272
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000273 def __delitem__(self, elem):
274 'Like dict.__delitem__() but does not raise KeyError for missing values.'
275 if elem in self:
276 dict.__delitem__(self, elem)
277
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000278 def __repr__(self):
279 if not self:
280 return '%s()' % self.__class__.__name__
281 items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
282 return '%s({%s})' % (self.__class__.__name__, items)
283
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000284 # Multiset-style mathematical operations discussed in:
285 # Knuth TAOCP Volume II section 4.6.3 exercise 19
286 # and at http://en.wikipedia.org/wiki/Multiset
287 #
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000288 # Outputs guaranteed to only include positive counts.
289 #
290 # To strip negative and zero counts, add-in an empty counter:
291 # c += Counter()
292
293 def __add__(self, other):
294 '''Add counts from two counters.
295
296 >>> Counter('abbb') + Counter('bcc')
297 Counter({'b': 4, 'c': 2, 'a': 1})
298
299 '''
300 if not isinstance(other, Counter):
301 return NotImplemented
302 result = Counter()
303 for elem in set(self) | set(other):
304 newcount = self[elem] + other[elem]
305 if newcount > 0:
306 result[elem] = newcount
307 return result
308
309 def __sub__(self, other):
310 ''' Subtract count, but keep only results with positive counts.
311
312 >>> Counter('abbbc') - Counter('bccd')
313 Counter({'b': 2, 'a': 1})
314
315 '''
316 if not isinstance(other, Counter):
317 return NotImplemented
318 result = Counter()
Raymond Hettingere0d1b9f2009-01-21 20:36:27 +0000319 for elem in set(self) | set(other):
320 newcount = self[elem] - other[elem]
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000321 if newcount > 0:
322 result[elem] = newcount
323 return result
324
325 def __or__(self, other):
326 '''Union is the maximum of value in either of the input counters.
327
328 >>> Counter('abbb') | Counter('bcc')
329 Counter({'b': 3, 'c': 2, 'a': 1})
330
331 '''
332 if not isinstance(other, Counter):
333 return NotImplemented
334 _max = max
335 result = Counter()
336 for elem in set(self) | set(other):
337 newcount = _max(self[elem], other[elem])
338 if newcount > 0:
339 result[elem] = newcount
340 return result
341
342 def __and__(self, other):
343 ''' Intersection is the minimum of corresponding counts.
344
345 >>> Counter('abbb') & Counter('bcc')
346 Counter({'b': 1})
347
348 '''
349 if not isinstance(other, Counter):
350 return NotImplemented
351 _min = min
352 result = Counter()
353 if len(self) < len(other):
354 self, other = other, self
355 for elem in filter(self.__contains__, other):
356 newcount = _min(self[elem], other[elem])
357 if newcount > 0:
358 result[elem] = newcount
359 return result
360
Guido van Rossumd8faa362007-04-27 19:54:29 +0000361
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000362################################################################################
363### UserDict
364################################################################################
Guido van Rossumd8faa362007-04-27 19:54:29 +0000365
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000366class UserDict(MutableMapping):
367
368 # Start by filling-out the abstract methods
369 def __init__(self, dict=None, **kwargs):
370 self.data = {}
371 if dict is not None:
372 self.update(dict)
373 if len(kwargs):
374 self.update(kwargs)
375 def __len__(self): return len(self.data)
376 def __getitem__(self, key):
377 if key in self.data:
378 return self.data[key]
379 if hasattr(self.__class__, "__missing__"):
380 return self.__class__.__missing__(self, key)
381 raise KeyError(key)
382 def __setitem__(self, key, item): self.data[key] = item
383 def __delitem__(self, key): del self.data[key]
384 def __iter__(self):
385 return iter(self.data)
386
Raymond Hettinger554c8b82008-02-05 22:54:43 +0000387 # Modify __contains__ to work correctly when __missing__ is present
388 def __contains__(self, key):
389 return key in self.data
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000390
391 # Now, add the methods in dicts but not in MutableMapping
392 def __repr__(self): return repr(self.data)
393 def copy(self):
394 if self.__class__ is UserDict:
395 return UserDict(self.data.copy())
396 import copy
397 data = self.data
398 try:
399 self.data = {}
400 c = copy.copy(self)
401 finally:
402 self.data = data
403 c.update(self)
404 return c
405 @classmethod
406 def fromkeys(cls, iterable, value=None):
407 d = cls()
408 for key in iterable:
409 d[key] = value
410 return d
411
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000412
413
414################################################################################
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000415### UserList
416################################################################################
417
418class UserList(MutableSequence):
419 """A more or less complete user-defined wrapper around list objects."""
420 def __init__(self, initlist=None):
421 self.data = []
422 if initlist is not None:
423 # XXX should this accept an arbitrary sequence?
424 if type(initlist) == type(self.data):
425 self.data[:] = initlist
426 elif isinstance(initlist, UserList):
427 self.data[:] = initlist.data[:]
428 else:
429 self.data = list(initlist)
430 def __repr__(self): return repr(self.data)
431 def __lt__(self, other): return self.data < self.__cast(other)
432 def __le__(self, other): return self.data <= self.__cast(other)
433 def __eq__(self, other): return self.data == self.__cast(other)
434 def __ne__(self, other): return self.data != self.__cast(other)
435 def __gt__(self, other): return self.data > self.__cast(other)
436 def __ge__(self, other): return self.data >= self.__cast(other)
437 def __cast(self, other):
438 return other.data if isinstance(other, UserList) else other
439 def __cmp__(self, other):
440 return cmp(self.data, self.__cast(other))
441 def __contains__(self, item): return item in self.data
442 def __len__(self): return len(self.data)
443 def __getitem__(self, i): return self.data[i]
444 def __setitem__(self, i, item): self.data[i] = item
445 def __delitem__(self, i): del self.data[i]
446 def __add__(self, other):
447 if isinstance(other, UserList):
448 return self.__class__(self.data + other.data)
449 elif isinstance(other, type(self.data)):
450 return self.__class__(self.data + other)
451 return self.__class__(self.data + list(other))
452 def __radd__(self, other):
453 if isinstance(other, UserList):
454 return self.__class__(other.data + self.data)
455 elif isinstance(other, type(self.data)):
456 return self.__class__(other + self.data)
457 return self.__class__(list(other) + self.data)
458 def __iadd__(self, other):
459 if isinstance(other, UserList):
460 self.data += other.data
461 elif isinstance(other, type(self.data)):
462 self.data += other
463 else:
464 self.data += list(other)
465 return self
466 def __mul__(self, n):
467 return self.__class__(self.data*n)
468 __rmul__ = __mul__
469 def __imul__(self, n):
470 self.data *= n
471 return self
472 def append(self, item): self.data.append(item)
473 def insert(self, i, item): self.data.insert(i, item)
474 def pop(self, i=-1): return self.data.pop(i)
475 def remove(self, item): self.data.remove(item)
476 def count(self, item): return self.data.count(item)
477 def index(self, item, *args): return self.data.index(item, *args)
478 def reverse(self): self.data.reverse()
479 def sort(self, *args, **kwds): self.data.sort(*args, **kwds)
480 def extend(self, other):
481 if isinstance(other, UserList):
482 self.data.extend(other.data)
483 else:
484 self.data.extend(other)
485
486
487
488################################################################################
Raymond Hettingerb3a65f82008-02-21 22:11:37 +0000489### UserString
490################################################################################
491
492class UserString(Sequence):
493 def __init__(self, seq):
494 if isinstance(seq, str):
495 self.data = seq
496 elif isinstance(seq, UserString):
497 self.data = seq.data[:]
498 else:
499 self.data = str(seq)
500 def __str__(self): return str(self.data)
501 def __repr__(self): return repr(self.data)
502 def __int__(self): return int(self.data)
Raymond Hettingerb3a65f82008-02-21 22:11:37 +0000503 def __float__(self): return float(self.data)
504 def __complex__(self): return complex(self.data)
505 def __hash__(self): return hash(self.data)
506
507 def __eq__(self, string):
508 if isinstance(string, UserString):
509 return self.data == string.data
510 return self.data == string
511 def __ne__(self, string):
512 if isinstance(string, UserString):
513 return self.data != string.data
514 return self.data != string
515 def __lt__(self, string):
516 if isinstance(string, UserString):
517 return self.data < string.data
518 return self.data < string
519 def __le__(self, string):
520 if isinstance(string, UserString):
521 return self.data <= string.data
522 return self.data <= string
523 def __gt__(self, string):
524 if isinstance(string, UserString):
525 return self.data > string.data
526 return self.data > string
527 def __ge__(self, string):
528 if isinstance(string, UserString):
529 return self.data >= string.data
530 return self.data >= string
531
532 def __contains__(self, char):
533 if isinstance(char, UserString):
534 char = char.data
535 return char in self.data
536
537 def __len__(self): return len(self.data)
538 def __getitem__(self, index): return self.__class__(self.data[index])
539 def __add__(self, other):
540 if isinstance(other, UserString):
541 return self.__class__(self.data + other.data)
542 elif isinstance(other, str):
543 return self.__class__(self.data + other)
544 return self.__class__(self.data + str(other))
545 def __radd__(self, other):
546 if isinstance(other, str):
547 return self.__class__(other + self.data)
548 return self.__class__(str(other) + self.data)
549 def __mul__(self, n):
550 return self.__class__(self.data*n)
551 __rmul__ = __mul__
552 def __mod__(self, args):
553 return self.__class__(self.data % args)
554
555 # the following methods are defined in alphabetical order:
556 def capitalize(self): return self.__class__(self.data.capitalize())
557 def center(self, width, *args):
558 return self.__class__(self.data.center(width, *args))
559 def count(self, sub, start=0, end=_sys.maxsize):
560 if isinstance(sub, UserString):
561 sub = sub.data
562 return self.data.count(sub, start, end)
563 def encode(self, encoding=None, errors=None): # XXX improve this?
564 if encoding:
565 if errors:
566 return self.__class__(self.data.encode(encoding, errors))
567 return self.__class__(self.data.encode(encoding))
568 return self.__class__(self.data.encode())
569 def endswith(self, suffix, start=0, end=_sys.maxsize):
570 return self.data.endswith(suffix, start, end)
571 def expandtabs(self, tabsize=8):
572 return self.__class__(self.data.expandtabs(tabsize))
573 def find(self, sub, start=0, end=_sys.maxsize):
574 if isinstance(sub, UserString):
575 sub = sub.data
576 return self.data.find(sub, start, end)
577 def format(self, *args, **kwds):
578 return self.data.format(*args, **kwds)
579 def index(self, sub, start=0, end=_sys.maxsize):
580 return self.data.index(sub, start, end)
581 def isalpha(self): return self.data.isalpha()
582 def isalnum(self): return self.data.isalnum()
583 def isdecimal(self): return self.data.isdecimal()
584 def isdigit(self): return self.data.isdigit()
585 def isidentifier(self): return self.data.isidentifier()
586 def islower(self): return self.data.islower()
587 def isnumeric(self): return self.data.isnumeric()
588 def isspace(self): return self.data.isspace()
589 def istitle(self): return self.data.istitle()
590 def isupper(self): return self.data.isupper()
591 def join(self, seq): return self.data.join(seq)
592 def ljust(self, width, *args):
593 return self.__class__(self.data.ljust(width, *args))
594 def lower(self): return self.__class__(self.data.lower())
595 def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars))
596 def partition(self, sep):
597 return self.data.partition(sep)
598 def replace(self, old, new, maxsplit=-1):
599 if isinstance(old, UserString):
600 old = old.data
601 if isinstance(new, UserString):
602 new = new.data
603 return self.__class__(self.data.replace(old, new, maxsplit))
604 def rfind(self, sub, start=0, end=_sys.maxsize):
605 return self.data.rfind(sub, start, end)
606 def rindex(self, sub, start=0, end=_sys.maxsize):
607 return self.data.rindex(sub, start, end)
608 def rjust(self, width, *args):
609 return self.__class__(self.data.rjust(width, *args))
610 def rpartition(self, sep):
611 return self.data.rpartition(sep)
612 def rstrip(self, chars=None):
613 return self.__class__(self.data.rstrip(chars))
614 def split(self, sep=None, maxsplit=-1):
615 return self.data.split(sep, maxsplit)
616 def rsplit(self, sep=None, maxsplit=-1):
617 return self.data.rsplit(sep, maxsplit)
618 def splitlines(self, keepends=0): return self.data.splitlines(keepends)
619 def startswith(self, prefix, start=0, end=_sys.maxsize):
620 return self.data.startswith(prefix, start, end)
621 def strip(self, chars=None): return self.__class__(self.data.strip(chars))
622 def swapcase(self): return self.__class__(self.data.swapcase())
623 def title(self): return self.__class__(self.data.title())
624 def translate(self, *args):
625 return self.__class__(self.data.translate(*args))
626 def upper(self): return self.__class__(self.data.upper())
627 def zfill(self, width): return self.__class__(self.data.zfill(width))
628
629
630
631################################################################################
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000632### Simple tests
633################################################################################
Guido van Rossumd8faa362007-04-27 19:54:29 +0000634
635if __name__ == '__main__':
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000636 # verify that instances can be pickled
Guido van Rossum99603b02007-07-20 00:22:32 +0000637 from pickle import loads, dumps
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000638 Point = namedtuple('Point', 'x, y', True)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000639 p = Point(x=10, y=20)
640 assert p == loads(dumps(p))
641
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000642 # test and demonstrate ability to override methods
Christian Heimes043d6f62008-01-07 17:19:16 +0000643 class Point(namedtuple('Point', 'x y')):
Christian Heimes25bb7832008-01-11 16:17:00 +0000644 __slots__ = ()
Christian Heimes043d6f62008-01-07 17:19:16 +0000645 @property
646 def hypot(self):
647 return (self.x ** 2 + self.y ** 2) ** 0.5
Christian Heimes790c8232008-01-07 21:14:23 +0000648 def __str__(self):
Christian Heimes25bb7832008-01-11 16:17:00 +0000649 return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot)
Christian Heimes043d6f62008-01-07 17:19:16 +0000650
Christian Heimes25bb7832008-01-11 16:17:00 +0000651 for p in Point(3, 4), Point(14, 5/7.):
Christian Heimes790c8232008-01-07 21:14:23 +0000652 print (p)
Christian Heimes043d6f62008-01-07 17:19:16 +0000653
654 class Point(namedtuple('Point', 'x y')):
655 'Point class with optimized _make() and _replace() without error-checking'
Christian Heimes25bb7832008-01-11 16:17:00 +0000656 __slots__ = ()
Christian Heimes043d6f62008-01-07 17:19:16 +0000657 _make = classmethod(tuple.__new__)
658 def _replace(self, _map=map, **kwds):
Christian Heimes2380ac72008-01-09 00:17:24 +0000659 return self._make(_map(kwds.get, ('x', 'y'), self))
Christian Heimes043d6f62008-01-07 17:19:16 +0000660
661 print(Point(11, 22)._replace(x=100))
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000662
Christian Heimes25bb7832008-01-11 16:17:00 +0000663 Point3D = namedtuple('Point3D', Point._fields + ('z',))
664 print(Point3D.__doc__)
665
Guido van Rossumd8faa362007-04-27 19:54:29 +0000666 import doctest
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000667 TestResults = namedtuple('TestResults', 'failed attempted')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000668 print(TestResults(*doctest.testmod()))