blob: 3d567e388e614a79cae7c88cbbf82da846c990d1 [file] [log] [blame]
Guido van Rossum64c06e32007-11-22 00:55:51 +00001# Copyright 2007 Google, Inc. All Rights Reserved.
2# Licensed to PSF under a Contributor Agreement.
3
4"""Abstract Base Classes (ABCs) for collections, according to PEP 3119.
5
6DON'T USE THIS MODULE DIRECTLY! The classes here should be imported
7via collections; they are defined here only to alleviate certain
8bootstrapping issues. Unit tests are in test_collections.
9"""
10
11from abc import ABCMeta, abstractmethod
Raymond Hettinger4c52f522008-06-23 03:29:28 +000012import sys
Guido van Rossum64c06e32007-11-22 00:55:51 +000013
14__all__ = ["Hashable", "Iterable", "Iterator",
15 "Sized", "Container", "Callable",
16 "Set", "MutableSet",
17 "Mapping", "MutableMapping",
18 "MappingView", "KeysView", "ItemsView", "ValuesView",
19 "Sequence", "MutableSequence",
20 ]
21
22### ONE-TRICK PONIES ###
23
Florent Xicluna47627d52010-03-08 15:20:28 +000024def _hasattr(C, attr):
25 try:
26 return any(attr in B.__dict__ for B in C.__mro__)
27 except AttributeError:
28 # Old-style class
29 return hasattr(C, attr)
30
31
Guido van Rossum64c06e32007-11-22 00:55:51 +000032class Hashable:
33 __metaclass__ = ABCMeta
34
35 @abstractmethod
36 def __hash__(self):
37 return 0
38
39 @classmethod
40 def __subclasshook__(cls, C):
41 if cls is Hashable:
Florent Xicluna47627d52010-03-08 15:20:28 +000042 try:
43 for B in C.__mro__:
44 if "__hash__" in B.__dict__:
45 if B.__dict__["__hash__"]:
46 return True
47 break
48 except AttributeError:
49 # Old-style class
50 if getattr(C, "__hash__", None):
51 return True
Guido van Rossum64c06e32007-11-22 00:55:51 +000052 return NotImplemented
53
54
55class Iterable:
56 __metaclass__ = ABCMeta
57
58 @abstractmethod
59 def __iter__(self):
60 while False:
61 yield None
62
63 @classmethod
64 def __subclasshook__(cls, C):
65 if cls is Iterable:
Florent Xicluna47627d52010-03-08 15:20:28 +000066 if _hasattr(C, "__iter__"):
Guido van Rossum64c06e32007-11-22 00:55:51 +000067 return True
68 return NotImplemented
69
70Iterable.register(str)
71
72
Raymond Hettingerc2bc0d12008-02-09 01:18:42 +000073class Iterator(Iterable):
Guido van Rossum64c06e32007-11-22 00:55:51 +000074
75 @abstractmethod
Raymond Hettingerf779e6f2009-01-28 23:02:26 +000076 def next(self):
Raymond Hettingercce5b042013-03-24 14:54:25 -070077 'Return the next item from the iterator. When exhausted, raise StopIteration'
Guido van Rossum64c06e32007-11-22 00:55:51 +000078 raise StopIteration
79
80 def __iter__(self):
81 return self
82
83 @classmethod
84 def __subclasshook__(cls, C):
85 if cls is Iterator:
Alexander Belopolsky1fea5c42010-11-30 01:18:17 +000086 if _hasattr(C, "next") and _hasattr(C, "__iter__"):
Guido van Rossum64c06e32007-11-22 00:55:51 +000087 return True
88 return NotImplemented
89
90
91class Sized:
92 __metaclass__ = ABCMeta
93
94 @abstractmethod
95 def __len__(self):
96 return 0
97
98 @classmethod
99 def __subclasshook__(cls, C):
100 if cls is Sized:
Florent Xicluna47627d52010-03-08 15:20:28 +0000101 if _hasattr(C, "__len__"):
Guido van Rossum64c06e32007-11-22 00:55:51 +0000102 return True
103 return NotImplemented
104
105
106class Container:
107 __metaclass__ = ABCMeta
108
109 @abstractmethod
110 def __contains__(self, x):
111 return False
112
113 @classmethod
114 def __subclasshook__(cls, C):
115 if cls is Container:
Florent Xicluna47627d52010-03-08 15:20:28 +0000116 if _hasattr(C, "__contains__"):
Guido van Rossum64c06e32007-11-22 00:55:51 +0000117 return True
118 return NotImplemented
119
120
121class Callable:
122 __metaclass__ = ABCMeta
123
124 @abstractmethod
Raymond Hettinger10ac19b2008-03-03 22:19:58 +0000125 def __call__(self, *args, **kwds):
Guido van Rossum64c06e32007-11-22 00:55:51 +0000126 return False
127
128 @classmethod
129 def __subclasshook__(cls, C):
130 if cls is Callable:
Florent Xicluna47627d52010-03-08 15:20:28 +0000131 if _hasattr(C, "__call__"):
Guido van Rossum64c06e32007-11-22 00:55:51 +0000132 return True
133 return NotImplemented
134
135
136### SETS ###
137
138
Raymond Hettingerc2bc0d12008-02-09 01:18:42 +0000139class Set(Sized, Iterable, Container):
Guido van Rossum64c06e32007-11-22 00:55:51 +0000140 """A set is a finite, iterable container.
141
142 This class provides concrete generic implementations of all
143 methods except for __contains__, __iter__ and __len__.
144
145 To override the comparisons (presumably for speed, as the
Raymond Hettinger809b6652014-07-03 00:30:52 +0100146 semantics are fixed), redefine __le__ and __ge__,
Guido van Rossum64c06e32007-11-22 00:55:51 +0000147 then the other operations will automatically follow suit.
148 """
149
Guido van Rossum64c06e32007-11-22 00:55:51 +0000150 def __le__(self, other):
151 if not isinstance(other, Set):
152 return NotImplemented
153 if len(self) > len(other):
154 return False
155 for elem in self:
156 if elem not in other:
157 return False
158 return True
159
160 def __lt__(self, other):
161 if not isinstance(other, Set):
162 return NotImplemented
163 return len(self) < len(other) and self.__le__(other)
164
Raymond Hettingerd53f1c42008-02-08 23:34:21 +0000165 def __gt__(self, other):
166 if not isinstance(other, Set):
167 return NotImplemented
Raymond Hettingerf643b9a2014-05-25 22:13:41 -0700168 return len(self) > len(other) and self.__ge__(other)
Raymond Hettingerd53f1c42008-02-08 23:34:21 +0000169
170 def __ge__(self, other):
171 if not isinstance(other, Set):
172 return NotImplemented
Raymond Hettingerf643b9a2014-05-25 22:13:41 -0700173 if len(self) < len(other):
174 return False
175 for elem in other:
176 if elem not in self:
177 return False
178 return True
Raymond Hettingerd53f1c42008-02-08 23:34:21 +0000179
Guido van Rossum64c06e32007-11-22 00:55:51 +0000180 def __eq__(self, other):
181 if not isinstance(other, Set):
182 return NotImplemented
183 return len(self) == len(other) and self.__le__(other)
184
Raymond Hettingerd53f1c42008-02-08 23:34:21 +0000185 def __ne__(self, other):
186 return not (self == other)
187
Guido van Rossum64c06e32007-11-22 00:55:51 +0000188 @classmethod
189 def _from_iterable(cls, it):
Raymond Hettinger017b6a32008-02-07 03:10:33 +0000190 '''Construct an instance of the class from any iterable input.
191
192 Must override this method if the class constructor signature
Raymond Hettinger2e827bf2008-02-09 03:34:52 +0000193 does not accept an iterable for an input.
Raymond Hettinger017b6a32008-02-07 03:10:33 +0000194 '''
Raymond Hettinger2e827bf2008-02-09 03:34:52 +0000195 return cls(it)
Guido van Rossum64c06e32007-11-22 00:55:51 +0000196
197 def __and__(self, other):
198 if not isinstance(other, Iterable):
199 return NotImplemented
200 return self._from_iterable(value for value in other if value in self)
201
Raymond Hettingerf643b9a2014-05-25 22:13:41 -0700202 __rand__ = __and__
203
Raymond Hettingerabf3fcf2008-01-30 00:01:07 +0000204 def isdisjoint(self, other):
Raymond Hettingercce5b042013-03-24 14:54:25 -0700205 'Return True if two sets have a null intersection.'
Raymond Hettingerabf3fcf2008-01-30 00:01:07 +0000206 for value in other:
207 if value in self:
208 return False
209 return True
210
Guido van Rossum64c06e32007-11-22 00:55:51 +0000211 def __or__(self, other):
212 if not isinstance(other, Iterable):
213 return NotImplemented
Raymond Hettinger972fb072008-03-03 22:04:55 +0000214 chain = (e for s in (self, other) for e in s)
215 return self._from_iterable(chain)
Guido van Rossum64c06e32007-11-22 00:55:51 +0000216
Raymond Hettingerf643b9a2014-05-25 22:13:41 -0700217 __ror__ = __or__
218
Guido van Rossum64c06e32007-11-22 00:55:51 +0000219 def __sub__(self, other):
220 if not isinstance(other, Set):
221 if not isinstance(other, Iterable):
222 return NotImplemented
223 other = self._from_iterable(other)
224 return self._from_iterable(value for value in self
225 if value not in other)
226
Raymond Hettingerf643b9a2014-05-25 22:13:41 -0700227 def __rsub__(self, other):
228 if not isinstance(other, Set):
229 if not isinstance(other, Iterable):
230 return NotImplemented
231 other = self._from_iterable(other)
232 return self._from_iterable(value for value in other
233 if value not in self)
234
Guido van Rossum64c06e32007-11-22 00:55:51 +0000235 def __xor__(self, other):
236 if not isinstance(other, Set):
237 if not isinstance(other, Iterable):
238 return NotImplemented
239 other = self._from_iterable(other)
240 return (self - other) | (other - self)
241
Raymond Hettingerf643b9a2014-05-25 22:13:41 -0700242 __rxor__ = __xor__
243
Nick Coghlan48361f52008-08-11 15:45:58 +0000244 # Sets are not hashable by default, but subclasses can change this
245 __hash__ = None
246
Guido van Rossum64c06e32007-11-22 00:55:51 +0000247 def _hash(self):
248 """Compute the hash value of a set.
249
250 Note that we don't define __hash__: not all sets are hashable.
251 But if you define a hashable set type, its __hash__ should
252 call this function.
253
254 This must be compatible __eq__.
255
256 All sets ought to compare equal if they contain the same
257 elements, regardless of how they are implemented, and
258 regardless of the order of the elements; so there's not much
259 freedom for __eq__ or __hash__. We match the algorithm used
260 by the built-in frozenset type.
261 """
262 MAX = sys.maxint
263 MASK = 2 * MAX + 1
264 n = len(self)
265 h = 1927868237 * (n + 1)
266 h &= MASK
267 for x in self:
268 hx = hash(x)
269 h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167
270 h &= MASK
271 h = h * 69069 + 907133923
272 h &= MASK
273 if h > MAX:
274 h -= MASK + 1
275 if h == -1:
276 h = 590923713
277 return h
278
279Set.register(frozenset)
280
281
282class MutableSet(Set):
Raymond Hettingercce5b042013-03-24 14:54:25 -0700283 """A mutable set is a finite, iterable container.
284
285 This class provides concrete generic implementations of all
286 methods except for __contains__, __iter__, __len__,
287 add(), and discard().
288
289 To override the comparisons (presumably for speed, as the
290 semantics are fixed), all you have to do is redefine __le__ and
291 then the other operations will automatically follow suit.
292 """
Guido van Rossum64c06e32007-11-22 00:55:51 +0000293
294 @abstractmethod
295 def add(self, value):
Raymond Hettinger2d21d502009-01-13 09:08:32 +0000296 """Add an element."""
Guido van Rossum64c06e32007-11-22 00:55:51 +0000297 raise NotImplementedError
298
299 @abstractmethod
300 def discard(self, value):
Raymond Hettinger2d21d502009-01-13 09:08:32 +0000301 """Remove an element. Do not raise an exception if absent."""
Guido van Rossum64c06e32007-11-22 00:55:51 +0000302 raise NotImplementedError
303
Raymond Hettinger7d518f42008-01-30 00:08:31 +0000304 def remove(self, value):
305 """Remove an element. If not a member, raise a KeyError."""
306 if value not in self:
307 raise KeyError(value)
308 self.discard(value)
309
Guido van Rossum64c06e32007-11-22 00:55:51 +0000310 def pop(self):
311 """Return the popped value. Raise KeyError if empty."""
312 it = iter(self)
313 try:
Raymond Hettingerf779e6f2009-01-28 23:02:26 +0000314 value = next(it)
Guido van Rossum64c06e32007-11-22 00:55:51 +0000315 except StopIteration:
316 raise KeyError
317 self.discard(value)
318 return value
319
Guido van Rossum64c06e32007-11-22 00:55:51 +0000320 def clear(self):
321 """This is slow (creates N new iterators!) but effective."""
322 try:
323 while True:
324 self.pop()
325 except KeyError:
326 pass
327
328 def __ior__(self, it):
329 for value in it:
330 self.add(value)
331 return self
332
Raymond Hettinger66c4a6b2009-04-01 18:50:56 +0000333 def __iand__(self, it):
334 for value in (self - it):
335 self.discard(value)
Guido van Rossum64c06e32007-11-22 00:55:51 +0000336 return self
337
338 def __ixor__(self, it):
Daniel Stutzbach91287322010-08-24 21:09:30 +0000339 if it is self:
340 self.clear()
341 else:
342 if not isinstance(it, Set):
343 it = self._from_iterable(it)
344 for value in it:
345 if value in self:
346 self.discard(value)
347 else:
348 self.add(value)
Raymond Hettingere973c612008-01-31 01:42:11 +0000349 return self
Guido van Rossum64c06e32007-11-22 00:55:51 +0000350
351 def __isub__(self, it):
Daniel Stutzbach91287322010-08-24 21:09:30 +0000352 if it is self:
353 self.clear()
354 else:
355 for value in it:
356 self.discard(value)
Guido van Rossum64c06e32007-11-22 00:55:51 +0000357 return self
358
359MutableSet.register(set)
360
361
362### MAPPINGS ###
363
364
Raymond Hettingerc2bc0d12008-02-09 01:18:42 +0000365class Mapping(Sized, Iterable, Container):
Guido van Rossum64c06e32007-11-22 00:55:51 +0000366
Raymond Hettingercce5b042013-03-24 14:54:25 -0700367 """A Mapping is a generic container for associating key/value
368 pairs.
369
370 This class provides concrete generic implementations of all
371 methods except for __getitem__, __iter__, and __len__.
372
373 """
374
Guido van Rossum64c06e32007-11-22 00:55:51 +0000375 @abstractmethod
376 def __getitem__(self, key):
377 raise KeyError
378
379 def get(self, key, default=None):
Raymond Hettingercce5b042013-03-24 14:54:25 -0700380 'D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.'
Guido van Rossum64c06e32007-11-22 00:55:51 +0000381 try:
382 return self[key]
383 except KeyError:
384 return default
385
386 def __contains__(self, key):
387 try:
388 self[key]
389 except KeyError:
390 return False
391 else:
392 return True
393
Georg Brandl60fbf7f2008-06-07 17:03:28 +0000394 def iterkeys(self):
Raymond Hettingercce5b042013-03-24 14:54:25 -0700395 'D.iterkeys() -> an iterator over the keys of D'
Georg Brandl60fbf7f2008-06-07 17:03:28 +0000396 return iter(self)
397
398 def itervalues(self):
Raymond Hettingercce5b042013-03-24 14:54:25 -0700399 'D.itervalues() -> an iterator over the values of D'
Georg Brandl60fbf7f2008-06-07 17:03:28 +0000400 for key in self:
401 yield self[key]
402
403 def iteritems(self):
Raymond Hettingercce5b042013-03-24 14:54:25 -0700404 'D.iteritems() -> an iterator over the (key, value) items of D'
Georg Brandl60fbf7f2008-06-07 17:03:28 +0000405 for key in self:
406 yield (key, self[key])
407
Guido van Rossum64c06e32007-11-22 00:55:51 +0000408 def keys(self):
Raymond Hettingercce5b042013-03-24 14:54:25 -0700409 "D.keys() -> list of D's keys"
Georg Brandl60fbf7f2008-06-07 17:03:28 +0000410 return list(self)
Guido van Rossum64c06e32007-11-22 00:55:51 +0000411
412 def items(self):
Raymond Hettingercce5b042013-03-24 14:54:25 -0700413 "D.items() -> list of D's (key, value) pairs, as 2-tuples"
Georg Brandl60fbf7f2008-06-07 17:03:28 +0000414 return [(key, self[key]) for key in self]
Guido van Rossum64c06e32007-11-22 00:55:51 +0000415
416 def values(self):
Raymond Hettingercce5b042013-03-24 14:54:25 -0700417 "D.values() -> list of D's values"
Georg Brandl60fbf7f2008-06-07 17:03:28 +0000418 return [self[key] for key in self]
Guido van Rossum64c06e32007-11-22 00:55:51 +0000419
Nick Coghlan48361f52008-08-11 15:45:58 +0000420 # Mappings are not hashable by default, but subclasses can change this
421 __hash__ = None
422
Raymond Hettinger45eda642008-02-06 01:49:00 +0000423 def __eq__(self, other):
Benjamin Petersoneb318d32010-05-21 20:51:45 +0000424 if not isinstance(other, Mapping):
425 return NotImplemented
426 return dict(self.items()) == dict(other.items())
Raymond Hettinger45eda642008-02-06 01:49:00 +0000427
428 def __ne__(self, other):
429 return not (self == other)
Guido van Rossum64c06e32007-11-22 00:55:51 +0000430
Raymond Hettingerc2bc0d12008-02-09 01:18:42 +0000431class MappingView(Sized):
Guido van Rossum64c06e32007-11-22 00:55:51 +0000432
433 def __init__(self, mapping):
434 self._mapping = mapping
435
436 def __len__(self):
437 return len(self._mapping)
438
Raymond Hettingerb31a6d02009-02-27 08:09:47 +0000439 def __repr__(self):
440 return '{0.__class__.__name__}({0._mapping!r})'.format(self)
441
Guido van Rossum64c06e32007-11-22 00:55:51 +0000442
443class KeysView(MappingView, Set):
444
Raymond Hettinger917bba12010-08-22 08:01:58 +0000445 @classmethod
446 def _from_iterable(self, it):
447 return set(it)
448
Guido van Rossum64c06e32007-11-22 00:55:51 +0000449 def __contains__(self, key):
450 return key in self._mapping
451
452 def __iter__(self):
453 for key in self._mapping:
454 yield key
455
Guido van Rossum64c06e32007-11-22 00:55:51 +0000456
457class ItemsView(MappingView, Set):
458
Raymond Hettinger917bba12010-08-22 08:01:58 +0000459 @classmethod
460 def _from_iterable(self, it):
461 return set(it)
462
Guido van Rossum64c06e32007-11-22 00:55:51 +0000463 def __contains__(self, item):
464 key, value = item
465 try:
466 v = self._mapping[key]
467 except KeyError:
468 return False
469 else:
470 return v == value
471
472 def __iter__(self):
473 for key in self._mapping:
474 yield (key, self._mapping[key])
475
Guido van Rossum64c06e32007-11-22 00:55:51 +0000476
477class ValuesView(MappingView):
478
479 def __contains__(self, value):
480 for key in self._mapping:
481 if value == self._mapping[key]:
482 return True
483 return False
484
485 def __iter__(self):
486 for key in self._mapping:
487 yield self._mapping[key]
488
Guido van Rossum64c06e32007-11-22 00:55:51 +0000489
490class MutableMapping(Mapping):
491
Raymond Hettingercce5b042013-03-24 14:54:25 -0700492 """A MutableMapping is a generic container for associating
493 key/value pairs.
494
495 This class provides concrete generic implementations of all
496 methods except for __getitem__, __setitem__, __delitem__,
497 __iter__, and __len__.
498
499 """
500
Guido van Rossum64c06e32007-11-22 00:55:51 +0000501 @abstractmethod
502 def __setitem__(self, key, value):
503 raise KeyError
504
505 @abstractmethod
506 def __delitem__(self, key):
507 raise KeyError
508
509 __marker = object()
510
511 def pop(self, key, default=__marker):
Raymond Hettingercce5b042013-03-24 14:54:25 -0700512 '''D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
513 If key is not found, d is returned if given, otherwise KeyError is raised.
514 '''
Guido van Rossum64c06e32007-11-22 00:55:51 +0000515 try:
516 value = self[key]
517 except KeyError:
518 if default is self.__marker:
519 raise
520 return default
521 else:
522 del self[key]
523 return value
524
525 def popitem(self):
Raymond Hettingercce5b042013-03-24 14:54:25 -0700526 '''D.popitem() -> (k, v), remove and return some (key, value) pair
527 as a 2-tuple; but raise KeyError if D is empty.
528 '''
Guido van Rossum64c06e32007-11-22 00:55:51 +0000529 try:
530 key = next(iter(self))
531 except StopIteration:
532 raise KeyError
533 value = self[key]
534 del self[key]
535 return key, value
536
537 def clear(self):
Raymond Hettingercce5b042013-03-24 14:54:25 -0700538 'D.clear() -> None. Remove all items from D.'
Guido van Rossum64c06e32007-11-22 00:55:51 +0000539 try:
540 while True:
541 self.popitem()
542 except KeyError:
543 pass
544
Mark Dickinson42add992010-07-11 19:17:28 +0000545 def update(*args, **kwds):
Raymond Hettingercce5b042013-03-24 14:54:25 -0700546 ''' D.update([E, ]**F) -> None. Update D from mapping/iterable E and F.
547 If E present and has a .keys() method, does: for k in E: D[k] = E[k]
548 If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
549 In either case, this is followed by: for k, v in F.items(): D[k] = v
550 '''
Mark Dickinson42add992010-07-11 19:17:28 +0000551 if len(args) > 2:
552 raise TypeError("update() takes at most 2 positional "
553 "arguments ({} given)".format(len(args)))
554 elif not args:
555 raise TypeError("update() takes at least 1 argument (0 given)")
556 self = args[0]
557 other = args[1] if len(args) >= 2 else ()
558
Guido van Rossum64c06e32007-11-22 00:55:51 +0000559 if isinstance(other, Mapping):
560 for key in other:
561 self[key] = other[key]
562 elif hasattr(other, "keys"):
563 for key in other.keys():
564 self[key] = other[key]
565 else:
566 for key, value in other:
567 self[key] = value
568 for key, value in kwds.items():
569 self[key] = value
570
Raymond Hettinger45eda642008-02-06 01:49:00 +0000571 def setdefault(self, key, default=None):
Raymond Hettingercce5b042013-03-24 14:54:25 -0700572 'D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D'
Raymond Hettinger45eda642008-02-06 01:49:00 +0000573 try:
574 return self[key]
575 except KeyError:
576 self[key] = default
577 return default
578
Guido van Rossum64c06e32007-11-22 00:55:51 +0000579MutableMapping.register(dict)
580
581
582### SEQUENCES ###
583
584
Raymond Hettingerc2bc0d12008-02-09 01:18:42 +0000585class Sequence(Sized, Iterable, Container):
Guido van Rossum64c06e32007-11-22 00:55:51 +0000586 """All the operations on a read-only sequence.
587
588 Concrete subclasses must override __new__ or __init__,
589 __getitem__, and __len__.
590 """
591
592 @abstractmethod
593 def __getitem__(self, index):
594 raise IndexError
595
Guido van Rossum64c06e32007-11-22 00:55:51 +0000596 def __iter__(self):
597 i = 0
Raymond Hettinger18a1ffc2008-02-08 23:02:27 +0000598 try:
599 while True:
Guido van Rossum64c06e32007-11-22 00:55:51 +0000600 v = self[i]
Raymond Hettinger18a1ffc2008-02-08 23:02:27 +0000601 yield v
602 i += 1
603 except IndexError:
604 return
Guido van Rossum64c06e32007-11-22 00:55:51 +0000605
606 def __contains__(self, value):
607 for v in self:
608 if v == value:
609 return True
610 return False
611
612 def __reversed__(self):
613 for i in reversed(range(len(self))):
614 yield self[i]
615
616 def index(self, value):
Raymond Hettingercce5b042013-03-24 14:54:25 -0700617 '''S.index(value) -> integer -- return first index of value.
618 Raises ValueError if the value is not present.
619 '''
Guido van Rossum64c06e32007-11-22 00:55:51 +0000620 for i, v in enumerate(self):
621 if v == value:
622 return i
623 raise ValueError
624
625 def count(self, value):
Raymond Hettingercce5b042013-03-24 14:54:25 -0700626 'S.count(value) -> integer -- return number of occurrences of value'
Guido van Rossum64c06e32007-11-22 00:55:51 +0000627 return sum(1 for v in self if v == value)
628
629Sequence.register(tuple)
630Sequence.register(basestring)
631Sequence.register(buffer)
Raymond Hettinger8c56f882009-02-24 12:23:23 +0000632Sequence.register(xrange)
Guido van Rossum64c06e32007-11-22 00:55:51 +0000633
634
635class MutableSequence(Sequence):
636
Raymond Hettingercce5b042013-03-24 14:54:25 -0700637 """All the operations on a read-only sequence.
638
639 Concrete subclasses must provide __new__ or __init__,
640 __getitem__, __setitem__, __delitem__, __len__, and insert().
641
642 """
643
Guido van Rossum64c06e32007-11-22 00:55:51 +0000644 @abstractmethod
645 def __setitem__(self, index, value):
646 raise IndexError
647
648 @abstractmethod
649 def __delitem__(self, index):
650 raise IndexError
651
652 @abstractmethod
653 def insert(self, index, value):
Raymond Hettingercce5b042013-03-24 14:54:25 -0700654 'S.insert(index, object) -- insert object before index'
Guido van Rossum64c06e32007-11-22 00:55:51 +0000655 raise IndexError
656
657 def append(self, value):
Raymond Hettingercce5b042013-03-24 14:54:25 -0700658 'S.append(object) -- append object to the end of the sequence'
Guido van Rossum64c06e32007-11-22 00:55:51 +0000659 self.insert(len(self), value)
660
661 def reverse(self):
Raymond Hettingercce5b042013-03-24 14:54:25 -0700662 'S.reverse() -- reverse *IN PLACE*'
Guido van Rossum64c06e32007-11-22 00:55:51 +0000663 n = len(self)
664 for i in range(n//2):
665 self[i], self[n-i-1] = self[n-i-1], self[i]
666
667 def extend(self, values):
Raymond Hettingercce5b042013-03-24 14:54:25 -0700668 'S.extend(iterable) -- extend sequence by appending elements from the iterable'
Guido van Rossum64c06e32007-11-22 00:55:51 +0000669 for v in values:
670 self.append(v)
671
672 def pop(self, index=-1):
Raymond Hettingercce5b042013-03-24 14:54:25 -0700673 '''S.pop([index]) -> item -- remove and return item at index (default last).
674 Raise IndexError if list is empty or index is out of range.
675 '''
Guido van Rossum64c06e32007-11-22 00:55:51 +0000676 v = self[index]
677 del self[index]
678 return v
679
680 def remove(self, value):
Raymond Hettingercce5b042013-03-24 14:54:25 -0700681 '''S.remove(value) -- remove first occurrence of value.
682 Raise ValueError if the value is not present.
683 '''
Guido van Rossum64c06e32007-11-22 00:55:51 +0000684 del self[self.index(value)]
685
686 def __iadd__(self, values):
687 self.extend(values)
Raymond Hettingerfceb5d42009-05-18 15:51:59 +0000688 return self
Guido van Rossum64c06e32007-11-22 00:55:51 +0000689
690MutableSequence.register(list)