blob: 6c1abce9810c3375e2f443f38862349ecde6b782 [file] [log] [blame]
Brett Cannon23a4a7b2008-05-12 00:56:28 +00001__all__ = ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList',
2 'UserString']
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
174 def __init__(self, iterable=None):
175 '''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
182
183 '''
184 self.update(iterable)
185
186 def __missing__(self, key):
187 'The count of elements not in the Counter is zero.'
188 # Needed so that self[missing_item] does not raise KeyError
189 return 0
190
191 def most_common(self, n=None):
192 '''List the n most common elements and their counts from the most
193 common to the least. If n is None, then list all element counts.
194
195 >>> Counter('abracadabra').most_common(3)
196 [('a', 5), ('r', 2), ('b', 2)]
197
198 '''
199 # Emulate Bag.sortedByCount from Smalltalk
200 if n is None:
201 return sorted(self.items(), key=_itemgetter(1), reverse=True)
202 return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
203
204 def elements(self):
205 '''Iterator over elements repeating each as many times as its count.
206
207 >>> c = Counter('ABCABC')
208 >>> sorted(c.elements())
209 ['A', 'A', 'B', 'B', 'C', 'C']
210
211 # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1
212 >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
213 >>> product = 1
214 >>> for factor in prime_factors.elements(): # loop over factors
215 ... product *= factor # and multiply them
216 >>> product
217 1836
218
219 Note, if an element's count has been set to zero or is a negative
220 number, elements() will ignore it.
221
222 '''
223 # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
224 return _chain.from_iterable(_starmap(_repeat, self.items()))
225
226 # Override dict methods where necessary
227
228 @classmethod
229 def fromkeys(cls, iterable, v=None):
230 # There is no equivalent method for counters because setting v=1
231 # means that no element can have a count greater than one.
232 raise NotImplementedError(
233 'Counter.fromkeys() is undefined. Use Counter(iterable) instead.')
234
235 def update(self, iterable=None):
236 '''Like dict.update() but add counts instead of replacing them.
237
238 Source can be an iterable, a dictionary, or another Counter instance.
239
240 >>> c = Counter('which')
241 >>> c.update('witch') # add elements from another iterable
242 >>> d = Counter('watch')
243 >>> c.update(d) # add elements from another counter
244 >>> c['h'] # four 'h' in which, witch, and watch
245 4
246
247 '''
248 # The regular dict.update() operation makes no sense here because the
249 # replace behavior results in the some of original untouched counts
250 # being mixed-in with all of the other counts for a mismash that
251 # doesn't have a straight-forward interpretation in most counting
252 # contexts. Instead, we look to Knuth for suggested operations on
253 # multisets and implement the union-add operation discussed in
254 # TAOCP Volume II section 4.6.3 exercise 19. The Wikipedia entry for
255 # multisets calls that operation a sum or join.
256
257 if iterable is not None:
258 if isinstance(iterable, Mapping):
259 for elem, count in iterable.items():
260 self[elem] += count
261 else:
262 for elem in iterable:
263 self[elem] += 1
264
265 def copy(self):
266 'Like dict.copy() but returns a Counter instance instead of a dict.'
267 return Counter(self)
268
269 def __repr__(self):
270 if not self:
271 return '%s()' % self.__class__.__name__
272 items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
273 return '%s({%s})' % (self.__class__.__name__, items)
274
Guido van Rossumd8faa362007-04-27 19:54:29 +0000275
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000276################################################################################
277### UserDict
278################################################################################
Guido van Rossumd8faa362007-04-27 19:54:29 +0000279
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000280class UserDict(MutableMapping):
281
282 # Start by filling-out the abstract methods
283 def __init__(self, dict=None, **kwargs):
284 self.data = {}
285 if dict is not None:
286 self.update(dict)
287 if len(kwargs):
288 self.update(kwargs)
289 def __len__(self): return len(self.data)
290 def __getitem__(self, key):
291 if key in self.data:
292 return self.data[key]
293 if hasattr(self.__class__, "__missing__"):
294 return self.__class__.__missing__(self, key)
295 raise KeyError(key)
296 def __setitem__(self, key, item): self.data[key] = item
297 def __delitem__(self, key): del self.data[key]
298 def __iter__(self):
299 return iter(self.data)
300
Raymond Hettinger554c8b82008-02-05 22:54:43 +0000301 # Modify __contains__ to work correctly when __missing__ is present
302 def __contains__(self, key):
303 return key in self.data
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000304
305 # Now, add the methods in dicts but not in MutableMapping
306 def __repr__(self): return repr(self.data)
307 def copy(self):
308 if self.__class__ is UserDict:
309 return UserDict(self.data.copy())
310 import copy
311 data = self.data
312 try:
313 self.data = {}
314 c = copy.copy(self)
315 finally:
316 self.data = data
317 c.update(self)
318 return c
319 @classmethod
320 def fromkeys(cls, iterable, value=None):
321 d = cls()
322 for key in iterable:
323 d[key] = value
324 return d
325
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000326
327
328################################################################################
Raymond Hettinger53dbe392008-02-12 20:03:09 +0000329### UserList
330################################################################################
331
332class UserList(MutableSequence):
333 """A more or less complete user-defined wrapper around list objects."""
334 def __init__(self, initlist=None):
335 self.data = []
336 if initlist is not None:
337 # XXX should this accept an arbitrary sequence?
338 if type(initlist) == type(self.data):
339 self.data[:] = initlist
340 elif isinstance(initlist, UserList):
341 self.data[:] = initlist.data[:]
342 else:
343 self.data = list(initlist)
344 def __repr__(self): return repr(self.data)
345 def __lt__(self, other): return self.data < self.__cast(other)
346 def __le__(self, other): return self.data <= self.__cast(other)
347 def __eq__(self, other): return self.data == self.__cast(other)
348 def __ne__(self, other): return self.data != self.__cast(other)
349 def __gt__(self, other): return self.data > self.__cast(other)
350 def __ge__(self, other): return self.data >= self.__cast(other)
351 def __cast(self, other):
352 return other.data if isinstance(other, UserList) else other
353 def __cmp__(self, other):
354 return cmp(self.data, self.__cast(other))
355 def __contains__(self, item): return item in self.data
356 def __len__(self): return len(self.data)
357 def __getitem__(self, i): return self.data[i]
358 def __setitem__(self, i, item): self.data[i] = item
359 def __delitem__(self, i): del self.data[i]
360 def __add__(self, other):
361 if isinstance(other, UserList):
362 return self.__class__(self.data + other.data)
363 elif isinstance(other, type(self.data)):
364 return self.__class__(self.data + other)
365 return self.__class__(self.data + list(other))
366 def __radd__(self, other):
367 if isinstance(other, UserList):
368 return self.__class__(other.data + self.data)
369 elif isinstance(other, type(self.data)):
370 return self.__class__(other + self.data)
371 return self.__class__(list(other) + self.data)
372 def __iadd__(self, other):
373 if isinstance(other, UserList):
374 self.data += other.data
375 elif isinstance(other, type(self.data)):
376 self.data += other
377 else:
378 self.data += list(other)
379 return self
380 def __mul__(self, n):
381 return self.__class__(self.data*n)
382 __rmul__ = __mul__
383 def __imul__(self, n):
384 self.data *= n
385 return self
386 def append(self, item): self.data.append(item)
387 def insert(self, i, item): self.data.insert(i, item)
388 def pop(self, i=-1): return self.data.pop(i)
389 def remove(self, item): self.data.remove(item)
390 def count(self, item): return self.data.count(item)
391 def index(self, item, *args): return self.data.index(item, *args)
392 def reverse(self): self.data.reverse()
393 def sort(self, *args, **kwds): self.data.sort(*args, **kwds)
394 def extend(self, other):
395 if isinstance(other, UserList):
396 self.data.extend(other.data)
397 else:
398 self.data.extend(other)
399
400
401
402################################################################################
Raymond Hettingerb3a65f82008-02-21 22:11:37 +0000403### UserString
404################################################################################
405
406class UserString(Sequence):
407 def __init__(self, seq):
408 if isinstance(seq, str):
409 self.data = seq
410 elif isinstance(seq, UserString):
411 self.data = seq.data[:]
412 else:
413 self.data = str(seq)
414 def __str__(self): return str(self.data)
415 def __repr__(self): return repr(self.data)
416 def __int__(self): return int(self.data)
Raymond Hettingerb3a65f82008-02-21 22:11:37 +0000417 def __float__(self): return float(self.data)
418 def __complex__(self): return complex(self.data)
419 def __hash__(self): return hash(self.data)
420
421 def __eq__(self, string):
422 if isinstance(string, UserString):
423 return self.data == string.data
424 return self.data == string
425 def __ne__(self, string):
426 if isinstance(string, UserString):
427 return self.data != string.data
428 return self.data != string
429 def __lt__(self, string):
430 if isinstance(string, UserString):
431 return self.data < string.data
432 return self.data < string
433 def __le__(self, string):
434 if isinstance(string, UserString):
435 return self.data <= string.data
436 return self.data <= string
437 def __gt__(self, string):
438 if isinstance(string, UserString):
439 return self.data > string.data
440 return self.data > string
441 def __ge__(self, string):
442 if isinstance(string, UserString):
443 return self.data >= string.data
444 return self.data >= string
445
446 def __contains__(self, char):
447 if isinstance(char, UserString):
448 char = char.data
449 return char in self.data
450
451 def __len__(self): return len(self.data)
452 def __getitem__(self, index): return self.__class__(self.data[index])
453 def __add__(self, other):
454 if isinstance(other, UserString):
455 return self.__class__(self.data + other.data)
456 elif isinstance(other, str):
457 return self.__class__(self.data + other)
458 return self.__class__(self.data + str(other))
459 def __radd__(self, other):
460 if isinstance(other, str):
461 return self.__class__(other + self.data)
462 return self.__class__(str(other) + self.data)
463 def __mul__(self, n):
464 return self.__class__(self.data*n)
465 __rmul__ = __mul__
466 def __mod__(self, args):
467 return self.__class__(self.data % args)
468
469 # the following methods are defined in alphabetical order:
470 def capitalize(self): return self.__class__(self.data.capitalize())
471 def center(self, width, *args):
472 return self.__class__(self.data.center(width, *args))
473 def count(self, sub, start=0, end=_sys.maxsize):
474 if isinstance(sub, UserString):
475 sub = sub.data
476 return self.data.count(sub, start, end)
477 def encode(self, encoding=None, errors=None): # XXX improve this?
478 if encoding:
479 if errors:
480 return self.__class__(self.data.encode(encoding, errors))
481 return self.__class__(self.data.encode(encoding))
482 return self.__class__(self.data.encode())
483 def endswith(self, suffix, start=0, end=_sys.maxsize):
484 return self.data.endswith(suffix, start, end)
485 def expandtabs(self, tabsize=8):
486 return self.__class__(self.data.expandtabs(tabsize))
487 def find(self, sub, start=0, end=_sys.maxsize):
488 if isinstance(sub, UserString):
489 sub = sub.data
490 return self.data.find(sub, start, end)
491 def format(self, *args, **kwds):
492 return self.data.format(*args, **kwds)
493 def index(self, sub, start=0, end=_sys.maxsize):
494 return self.data.index(sub, start, end)
495 def isalpha(self): return self.data.isalpha()
496 def isalnum(self): return self.data.isalnum()
497 def isdecimal(self): return self.data.isdecimal()
498 def isdigit(self): return self.data.isdigit()
499 def isidentifier(self): return self.data.isidentifier()
500 def islower(self): return self.data.islower()
501 def isnumeric(self): return self.data.isnumeric()
502 def isspace(self): return self.data.isspace()
503 def istitle(self): return self.data.istitle()
504 def isupper(self): return self.data.isupper()
505 def join(self, seq): return self.data.join(seq)
506 def ljust(self, width, *args):
507 return self.__class__(self.data.ljust(width, *args))
508 def lower(self): return self.__class__(self.data.lower())
509 def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars))
510 def partition(self, sep):
511 return self.data.partition(sep)
512 def replace(self, old, new, maxsplit=-1):
513 if isinstance(old, UserString):
514 old = old.data
515 if isinstance(new, UserString):
516 new = new.data
517 return self.__class__(self.data.replace(old, new, maxsplit))
518 def rfind(self, sub, start=0, end=_sys.maxsize):
519 return self.data.rfind(sub, start, end)
520 def rindex(self, sub, start=0, end=_sys.maxsize):
521 return self.data.rindex(sub, start, end)
522 def rjust(self, width, *args):
523 return self.__class__(self.data.rjust(width, *args))
524 def rpartition(self, sep):
525 return self.data.rpartition(sep)
526 def rstrip(self, chars=None):
527 return self.__class__(self.data.rstrip(chars))
528 def split(self, sep=None, maxsplit=-1):
529 return self.data.split(sep, maxsplit)
530 def rsplit(self, sep=None, maxsplit=-1):
531 return self.data.rsplit(sep, maxsplit)
532 def splitlines(self, keepends=0): return self.data.splitlines(keepends)
533 def startswith(self, prefix, start=0, end=_sys.maxsize):
534 return self.data.startswith(prefix, start, end)
535 def strip(self, chars=None): return self.__class__(self.data.strip(chars))
536 def swapcase(self): return self.__class__(self.data.swapcase())
537 def title(self): return self.__class__(self.data.title())
538 def translate(self, *args):
539 return self.__class__(self.data.translate(*args))
540 def upper(self): return self.__class__(self.data.upper())
541 def zfill(self, width): return self.__class__(self.data.zfill(width))
542
543
544
545################################################################################
Raymond Hettinger48b8b662008-02-05 01:53:00 +0000546### Simple tests
547################################################################################
Guido van Rossumd8faa362007-04-27 19:54:29 +0000548
549if __name__ == '__main__':
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000550 # verify that instances can be pickled
Guido van Rossum99603b02007-07-20 00:22:32 +0000551 from pickle import loads, dumps
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000552 Point = namedtuple('Point', 'x, y', True)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000553 p = Point(x=10, y=20)
554 assert p == loads(dumps(p))
555
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000556 # test and demonstrate ability to override methods
Christian Heimes043d6f62008-01-07 17:19:16 +0000557 class Point(namedtuple('Point', 'x y')):
Christian Heimes25bb7832008-01-11 16:17:00 +0000558 __slots__ = ()
Christian Heimes043d6f62008-01-07 17:19:16 +0000559 @property
560 def hypot(self):
561 return (self.x ** 2 + self.y ** 2) ** 0.5
Christian Heimes790c8232008-01-07 21:14:23 +0000562 def __str__(self):
Christian Heimes25bb7832008-01-11 16:17:00 +0000563 return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot)
Christian Heimes043d6f62008-01-07 17:19:16 +0000564
Christian Heimes25bb7832008-01-11 16:17:00 +0000565 for p in Point(3, 4), Point(14, 5/7.):
Christian Heimes790c8232008-01-07 21:14:23 +0000566 print (p)
Christian Heimes043d6f62008-01-07 17:19:16 +0000567
568 class Point(namedtuple('Point', 'x y')):
569 'Point class with optimized _make() and _replace() without error-checking'
Christian Heimes25bb7832008-01-11 16:17:00 +0000570 __slots__ = ()
Christian Heimes043d6f62008-01-07 17:19:16 +0000571 _make = classmethod(tuple.__new__)
572 def _replace(self, _map=map, **kwds):
Christian Heimes2380ac72008-01-09 00:17:24 +0000573 return self._make(_map(kwds.get, ('x', 'y'), self))
Christian Heimes043d6f62008-01-07 17:19:16 +0000574
575 print(Point(11, 22)._replace(x=100))
Guido van Rossum3d392eb2007-11-16 00:35:22 +0000576
Christian Heimes25bb7832008-01-11 16:17:00 +0000577 Point3D = namedtuple('Point3D', Point._fields + ('z',))
578 print(Point3D.__doc__)
579
Guido van Rossumd8faa362007-04-27 19:54:29 +0000580 import doctest
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000581 TestResults = namedtuple('TestResults', 'failed attempted')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000582 print(TestResults(*doctest.testmod()))