blob: 45558f9b401e1804ae7907d605cc93ac8e6d93d2 [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'):
114 result.__module__ = _sys._getframe(1).f_globals['__name__']
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):
258 for elem, count in iterable.items():
259 self[elem] += count
260 else:
261 for elem in iterable:
262 self[elem] += 1
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000263 if kwds:
264 self.update(kwds)
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000265
266 def copy(self):
267 'Like dict.copy() but returns a Counter instance instead of a dict.'
268 return Counter(self)
269
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000270 def __delitem__(self, elem):
271 'Like dict.__delitem__() but does not raise KeyError for missing values.'
272 if elem in self:
273 dict.__delitem__(self, elem)
274
Raymond Hettingerb8baf632009-01-14 02:20:07 +0000275 def __repr__(self):
276 if not self:
277 return '%s()' % self.__class__.__name__
278 items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
279 return '%s({%s})' % (self.__class__.__name__, items)
280
Raymond Hettinger4d2073a2009-01-20 03:41:22 +0000281 # Multiset-style mathematical operations discussed in:
282 # Knuth TAOCP Volume II section 4.6.3 exercise 19
283 # and at http://en.wikipedia.org/wiki/Multiset
284 #
285 # Results are undefined when inputs contain negative counts.
286 # Outputs guaranteed to only include positive counts.
287 #
288 # To strip negative and zero counts, add-in an empty counter:
289 # c += Counter()
290
291 def __add__(self, other):
292 '''Add counts from two counters.
293
294 >>> Counter('abbb') + Counter('bcc')
295 Counter({'b': 4, 'c': 2, 'a': 1})
296
297 '''
298 if not isinstance(other, Counter):
299 return NotImplemented
300 result = Counter()
301 for elem in set(self) | set(other):
302 newcount = self[elem] + other[elem]
303 if newcount > 0:
304 result[elem] = newcount
305 return result
306
307 def __sub__(self, other):
308 ''' Subtract count, but keep only results with positive counts.
309
310 >>> Counter('abbbc') - Counter('bccd')
311 Counter({'b': 2, 'a': 1})
312
313 '''
314 if not isinstance(other, Counter):
315 return NotImplemented
316 result = Counter()
317 for elem, count in self.items():
318 newcount = count - other[elem]
319 if newcount > 0:
320 result[elem] = newcount
321 return result
322
323 def __or__(self, other):
324 '''Union is the maximum of value in either of the input counters.
325
326 >>> Counter('abbb') | Counter('bcc')
327 Counter({'b': 3, 'c': 2, 'a': 1})
328
329 '''
330 if not isinstance(other, Counter):
331 return NotImplemented
332 _max = max
333 result = Counter()
334 for elem in set(self) | set(other):
335 newcount = _max(self[elem], other[elem])
336 if newcount > 0:
337 result[elem] = newcount
338 return result
339
340 def __and__(self, other):
341 ''' Intersection is the minimum of corresponding counts.
342
343 >>> Counter('abbb') & Counter('bcc')
344 Counter({'b': 1})
345
346 '''
347 if not isinstance(other, Counter):
348 return NotImplemented
349 _min = min
350 result = Counter()
351 if len(self) < len(other):
352 self, other = other, self
353 for elem in filter(self.__contains__, other):
354 newcount = _min(self[elem], other[elem])
355 if newcount > 0:
356 result[elem] = newcount
357 return result
358
Guido van Rossumd8faa362007-04-27 19:54:29 +0000359
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000360################################################################################
361### UserDict
362################################################################################
Guido van Rossumd8faa362007-04-27 19:54:29 +0000363
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000364class UserDict(MutableMapping):
365
366 # Start by filling-out the abstract methods
367 def __init__(self, dict=None, **kwargs):
368 self.data = {}
369 if dict is not None:
370 self.update(dict)
371 if len(kwargs):
372 self.update(kwargs)
373 def __len__(self): return len(self.data)
374 def __getitem__(self, key):
375 if key in self.data:
376 return self.data[key]
377 if hasattr(self.__class__, "__missing__"):
378 return self.__class__.__missing__(self, key)
379 raise KeyError(key)
380 def __setitem__(self, key, item): self.data[key] = item
381 def __delitem__(self, key): del self.data[key]
382 def __iter__(self):
383 return iter(self.data)
384
Raymond Hettinger554c8b82008-02-05 22:54:43 +0000385 # Modify __contains__ to work correctly when __missing__ is present
386 def __contains__(self, key):
387 return key in self.data
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000388
389 # Now, add the methods in dicts but not in MutableMapping
390 def __repr__(self): return repr(self.data)
391 def copy(self):
392 if self.__class__ is UserDict:
393 return UserDict(self.data.copy())
394 import copy
395 data = self.data
396 try:
397 self.data = {}
398 c = copy.copy(self)
399 finally:
400 self.data = data
401 c.update(self)
402 return c
403 @classmethod
404 def fromkeys(cls, iterable, value=None):
405 d = cls()
406 for key in iterable:
407 d[key] = value
408 return d
409
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000410
411
412################################################################################
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000413### UserList
414################################################################################
415
416class UserList(MutableSequence):
417 """A more or less complete user-defined wrapper around list objects."""
418 def __init__(self, initlist=None):
419 self.data = []
420 if initlist is not None:
421 # XXX should this accept an arbitrary sequence?
422 if type(initlist) == type(self.data):
423 self.data[:] = initlist
424 elif isinstance(initlist, UserList):
425 self.data[:] = initlist.data[:]
426 else:
427 self.data = list(initlist)
428 def __repr__(self): return repr(self.data)
429 def __lt__(self, other): return self.data < self.__cast(other)
430 def __le__(self, other): return self.data <= self.__cast(other)
431 def __eq__(self, other): return self.data == self.__cast(other)
432 def __ne__(self, other): return self.data != self.__cast(other)
433 def __gt__(self, other): return self.data > self.__cast(other)
434 def __ge__(self, other): return self.data >= self.__cast(other)
435 def __cast(self, other):
436 return other.data if isinstance(other, UserList) else other
437 def __cmp__(self, other):
438 return cmp(self.data, self.__cast(other))
439 def __contains__(self, item): return item in self.data
440 def __len__(self): return len(self.data)
441 def __getitem__(self, i): return self.data[i]
442 def __setitem__(self, i, item): self.data[i] = item
443 def __delitem__(self, i): del self.data[i]
444 def __add__(self, other):
445 if isinstance(other, UserList):
446 return self.__class__(self.data + other.data)
447 elif isinstance(other, type(self.data)):
448 return self.__class__(self.data + other)
449 return self.__class__(self.data + list(other))
450 def __radd__(self, other):
451 if isinstance(other, UserList):
452 return self.__class__(other.data + self.data)
453 elif isinstance(other, type(self.data)):
454 return self.__class__(other + self.data)
455 return self.__class__(list(other) + self.data)
456 def __iadd__(self, other):
457 if isinstance(other, UserList):
458 self.data += other.data
459 elif isinstance(other, type(self.data)):
460 self.data += other
461 else:
462 self.data += list(other)
463 return self
464 def __mul__(self, n):
465 return self.__class__(self.data*n)
466 __rmul__ = __mul__
467 def __imul__(self, n):
468 self.data *= n
469 return self
470 def append(self, item): self.data.append(item)
471 def insert(self, i, item): self.data.insert(i, item)
472 def pop(self, i=-1): return self.data.pop(i)
473 def remove(self, item): self.data.remove(item)
474 def count(self, item): return self.data.count(item)
475 def index(self, item, *args): return self.data.index(item, *args)
476 def reverse(self): self.data.reverse()
477 def sort(self, *args, **kwds): self.data.sort(*args, **kwds)
478 def extend(self, other):
479 if isinstance(other, UserList):
480 self.data.extend(other.data)
481 else:
482 self.data.extend(other)
483
484
485
486################################################################################
Raymond Hettingerb3a65f82008-02-21 22:11:37 +0000487### UserString
488################################################################################
489
490class UserString(Sequence):
491 def __init__(self, seq):
492 if isinstance(seq, str):
493 self.data = seq
494 elif isinstance(seq, UserString):
495 self.data = seq.data[:]
496 else:
497 self.data = str(seq)
498 def __str__(self): return str(self.data)
499 def __repr__(self): return repr(self.data)
500 def __int__(self): return int(self.data)
Raymond Hettingerb3a65f82008-02-21 22:11:37 +0000501 def __float__(self): return float(self.data)
502 def __complex__(self): return complex(self.data)
503 def __hash__(self): return hash(self.data)
504
505 def __eq__(self, string):
506 if isinstance(string, UserString):
507 return self.data == string.data
508 return self.data == string
509 def __ne__(self, string):
510 if isinstance(string, UserString):
511 return self.data != string.data
512 return self.data != string
513 def __lt__(self, string):
514 if isinstance(string, UserString):
515 return self.data < string.data
516 return self.data < string
517 def __le__(self, string):
518 if isinstance(string, UserString):
519 return self.data <= string.data
520 return self.data <= string
521 def __gt__(self, string):
522 if isinstance(string, UserString):
523 return self.data > string.data
524 return self.data > string
525 def __ge__(self, string):
526 if isinstance(string, UserString):
527 return self.data >= string.data
528 return self.data >= string
529
530 def __contains__(self, char):
531 if isinstance(char, UserString):
532 char = char.data
533 return char in self.data
534
535 def __len__(self): return len(self.data)
536 def __getitem__(self, index): return self.__class__(self.data[index])
537 def __add__(self, other):
538 if isinstance(other, UserString):
539 return self.__class__(self.data + other.data)
540 elif isinstance(other, str):
541 return self.__class__(self.data + other)
542 return self.__class__(self.data + str(other))
543 def __radd__(self, other):
544 if isinstance(other, str):
545 return self.__class__(other + self.data)
546 return self.__class__(str(other) + self.data)
547 def __mul__(self, n):
548 return self.__class__(self.data*n)
549 __rmul__ = __mul__
550 def __mod__(self, args):
551 return self.__class__(self.data % args)
552
553 # the following methods are defined in alphabetical order:
554 def capitalize(self): return self.__class__(self.data.capitalize())
555 def center(self, width, *args):
556 return self.__class__(self.data.center(width, *args))
557 def count(self, sub, start=0, end=_sys.maxsize):
558 if isinstance(sub, UserString):
559 sub = sub.data
560 return self.data.count(sub, start, end)
561 def encode(self, encoding=None, errors=None): # XXX improve this?
562 if encoding:
563 if errors:
564 return self.__class__(self.data.encode(encoding, errors))
565 return self.__class__(self.data.encode(encoding))
566 return self.__class__(self.data.encode())
567 def endswith(self, suffix, start=0, end=_sys.maxsize):
568 return self.data.endswith(suffix, start, end)
569 def expandtabs(self, tabsize=8):
570 return self.__class__(self.data.expandtabs(tabsize))
571 def find(self, sub, start=0, end=_sys.maxsize):
572 if isinstance(sub, UserString):
573 sub = sub.data
574 return self.data.find(sub, start, end)
575 def format(self, *args, **kwds):
576 return self.data.format(*args, **kwds)
577 def index(self, sub, start=0, end=_sys.maxsize):
578 return self.data.index(sub, start, end)
579 def isalpha(self): return self.data.isalpha()
580 def isalnum(self): return self.data.isalnum()
581 def isdecimal(self): return self.data.isdecimal()
582 def isdigit(self): return self.data.isdigit()
583 def isidentifier(self): return self.data.isidentifier()
584 def islower(self): return self.data.islower()
585 def isnumeric(self): return self.data.isnumeric()
586 def isspace(self): return self.data.isspace()
587 def istitle(self): return self.data.istitle()
588 def isupper(self): return self.data.isupper()
589 def join(self, seq): return self.data.join(seq)
590 def ljust(self, width, *args):
591 return self.__class__(self.data.ljust(width, *args))
592 def lower(self): return self.__class__(self.data.lower())
593 def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars))
594 def partition(self, sep):
595 return self.data.partition(sep)
596 def replace(self, old, new, maxsplit=-1):
597 if isinstance(old, UserString):
598 old = old.data
599 if isinstance(new, UserString):
600 new = new.data
601 return self.__class__(self.data.replace(old, new, maxsplit))
602 def rfind(self, sub, start=0, end=_sys.maxsize):
603 return self.data.rfind(sub, start, end)
604 def rindex(self, sub, start=0, end=_sys.maxsize):
605 return self.data.rindex(sub, start, end)
606 def rjust(self, width, *args):
607 return self.__class__(self.data.rjust(width, *args))
608 def rpartition(self, sep):
609 return self.data.rpartition(sep)
610 def rstrip(self, chars=None):
611 return self.__class__(self.data.rstrip(chars))
612 def split(self, sep=None, maxsplit=-1):
613 return self.data.split(sep, maxsplit)
614 def rsplit(self, sep=None, maxsplit=-1):
615 return self.data.rsplit(sep, maxsplit)
616 def splitlines(self, keepends=0): return self.data.splitlines(keepends)
617 def startswith(self, prefix, start=0, end=_sys.maxsize):
618 return self.data.startswith(prefix, start, end)
619 def strip(self, chars=None): return self.__class__(self.data.strip(chars))
620 def swapcase(self): return self.__class__(self.data.swapcase())
621 def title(self): return self.__class__(self.data.title())
622 def translate(self, *args):
623 return self.__class__(self.data.translate(*args))
624 def upper(self): return self.__class__(self.data.upper())
625 def zfill(self, width): return self.__class__(self.data.zfill(width))
626
627
628
629################################################################################
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000630### Simple tests
631################################################################################
Guido van Rossumd8faa362007-04-27 19:54:29 +0000632
633if __name__ == '__main__':
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000634 # verify that instances can be pickled
Guido van Rossum99603b02007-07-20 00:22:32 +0000635 from pickle import loads, dumps
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000636 Point = namedtuple('Point', 'x, y', True)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000637 p = Point(x=10, y=20)
638 assert p == loads(dumps(p))
639
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000640 # test and demonstrate ability to override methods
Christian Heimes043d6f62008-01-07 17:19:16 +0000641 class Point(namedtuple('Point', 'x y')):
Christian Heimes25bb7832008-01-11 16:17:00 +0000642 __slots__ = ()
Christian Heimes043d6f62008-01-07 17:19:16 +0000643 @property
644 def hypot(self):
645 return (self.x ** 2 + self.y ** 2) ** 0.5
Christian Heimes790c8232008-01-07 21:14:23 +0000646 def __str__(self):
Christian Heimes25bb7832008-01-11 16:17:00 +0000647 return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot)
Christian Heimes043d6f62008-01-07 17:19:16 +0000648
Christian Heimes25bb7832008-01-11 16:17:00 +0000649 for p in Point(3, 4), Point(14, 5/7.):
Christian Heimes790c8232008-01-07 21:14:23 +0000650 print (p)
Christian Heimes043d6f62008-01-07 17:19:16 +0000651
652 class Point(namedtuple('Point', 'x y')):
653 'Point class with optimized _make() and _replace() without error-checking'
Christian Heimes25bb7832008-01-11 16:17:00 +0000654 __slots__ = ()
Christian Heimes043d6f62008-01-07 17:19:16 +0000655 _make = classmethod(tuple.__new__)
656 def _replace(self, _map=map, **kwds):
Christian Heimes2380ac72008-01-09 00:17:24 +0000657 return self._make(_map(kwds.get, ('x', 'y'), self))
Christian Heimes043d6f62008-01-07 17:19:16 +0000658
659 print(Point(11, 22)._replace(x=100))
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000660
Christian Heimes25bb7832008-01-11 16:17:00 +0000661 Point3D = namedtuple('Point3D', Point._fields + ('z',))
662 print(Point3D.__doc__)
663
Guido van Rossumd8faa362007-04-27 19:54:29 +0000664 import doctest
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000665 TestResults = namedtuple('TestResults', 'failed attempted')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000666 print(TestResults(*doctest.testmod()))