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