blob: 87302ac76d8019f1f1199b4bafa5fc590d56a07f [file] [log] [blame]
Guido van Rossumcd16bf62007-06-13 18:07:49 +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
Raymond Hettinger158c9c22011-02-22 00:41:50 +00006Unit tests are in test_collections.
Guido van Rossumcd16bf62007-06-13 18:07:49 +00007"""
8
9from abc import ABCMeta, abstractmethod
Benjamin Peterson41181742008-07-02 20:22:54 +000010import sys
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011
Guido van Rossum48b069a2020-04-07 09:50:06 -070012GenericAlias = type(list[int])
kj463c7d32020-12-14 02:38:24 +080013EllipsisType = type(...)
14def _f(): pass
15FunctionType = type(_f)
16del _f
Guido van Rossum48b069a2020-04-07 09:50:06 -070017
Yury Selivanov22214ab2016-11-16 18:25:04 -050018__all__ = ["Awaitable", "Coroutine",
19 "AsyncIterable", "AsyncIterator", "AsyncGenerator",
Guido van Rossum16ca06b2016-04-04 10:59:29 -070020 "Hashable", "Iterable", "Iterator", "Generator", "Reversible",
Guido van Rossumf0666942016-08-23 10:47:07 -070021 "Sized", "Container", "Callable", "Collection",
Guido van Rossumcd16bf62007-06-13 18:07:49 +000022 "Set", "MutableSet",
23 "Mapping", "MutableMapping",
24 "MappingView", "KeysView", "ItemsView", "ValuesView",
25 "Sequence", "MutableSequence",
Guido van Rossumd05eb002007-11-21 22:26:24 +000026 "ByteString",
Guido van Rossumcd16bf62007-06-13 18:07:49 +000027 ]
28
Christian Heimesbf235bd2013-10-13 02:21:33 +020029# This module has been renamed from collections.abc to _collections_abc to
30# speed up interpreter startup. Some of the types such as MutableMapping are
31# required early but collections module imports a lot of other modules.
32# See issue #19218
33__name__ = "collections.abc"
34
Raymond Hettinger02184282012-04-05 13:31:12 -070035# Private list of types that we want to register with the various ABCs
36# so that they will pass tests like:
37# it = iter(somebytearray)
38# assert isinstance(it, Iterable)
Serhiy Storchaka3bd9fde2016-10-08 21:33:59 +030039# Note: in other implementations, these types might not be distinct
40# and they may have their own implementation specific types that
Raymond Hettinger02184282012-04-05 13:31:12 -070041# are not included on this list.
Christian Heimesf83be4e2007-11-28 09:44:38 +000042bytes_iterator = type(iter(b''))
43bytearray_iterator = type(iter(bytearray()))
44#callable_iterator = ???
45dict_keyiterator = type(iter({}.keys()))
46dict_valueiterator = type(iter({}.values()))
47dict_itemiterator = type(iter({}.items()))
48list_iterator = type(iter([]))
49list_reverseiterator = type(iter(reversed([])))
50range_iterator = type(iter(range(0)))
Serhiy Storchaka48b1c3f2016-10-08 22:04:12 +030051longrange_iterator = type(iter(range(1 << 1000)))
Christian Heimesf83be4e2007-11-28 09:44:38 +000052set_iterator = type(iter(set()))
53str_iterator = type(iter(""))
54tuple_iterator = type(iter(()))
55zip_iterator = type(iter(zip()))
56## views ##
57dict_keys = type({}.keys())
58dict_values = type({}.values())
59dict_items = type({}.items())
Christian Heimes0db38532007-11-29 16:21:13 +000060## misc ##
Victor Stinner7b17a4e2012-04-20 01:41:36 +020061mappingproxy = type(type.__dict__)
Raymond Hettingerbd60e8d2015-05-09 01:07:23 -040062generator = type((lambda: (yield))())
Yury Selivanov5376ba92015-06-22 12:19:30 -040063## coroutine ##
64async def _coro(): pass
65_coro = _coro()
66coroutine = type(_coro)
67_coro.close() # Prevent ResourceWarning
68del _coro
Yury Selivanov22214ab2016-11-16 18:25:04 -050069## asynchronous generator ##
70async def _ag(): yield
71_ag = _ag()
72async_generator = type(_ag)
73del _ag
Christian Heimesf83be4e2007-11-28 09:44:38 +000074
75
Guido van Rossumcd16bf62007-06-13 18:07:49 +000076### ONE-TRICK PONIES ###
77
Guido van Rossum97c1adf2016-08-18 09:22:23 -070078def _check_methods(C, *methods):
79 mro = C.__mro__
80 for method in methods:
81 for B in mro:
82 if method in B.__dict__:
83 if B.__dict__[method] is None:
84 return NotImplemented
85 break
86 else:
87 return NotImplemented
88 return True
89
Guido van Rossumcd16bf62007-06-13 18:07:49 +000090class Hashable(metaclass=ABCMeta):
91
Raymond Hettingerc46759a2011-03-22 11:46:25 -070092 __slots__ = ()
93
Guido van Rossumcd16bf62007-06-13 18:07:49 +000094 @abstractmethod
95 def __hash__(self):
96 return 0
97
98 @classmethod
99 def __subclasshook__(cls, C):
100 if cls is Hashable:
Guido van Rossum97c1adf2016-08-18 09:22:23 -0700101 return _check_methods(C, "__hash__")
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000102 return NotImplemented
103
104
Yury Selivanovfdbeb2b2015-07-03 13:11:35 -0400105class Awaitable(metaclass=ABCMeta):
Yury Selivanov56fc6142015-05-29 09:01:29 -0400106
107 __slots__ = ()
108
109 @abstractmethod
110 def __await__(self):
111 yield
112
113 @classmethod
114 def __subclasshook__(cls, C):
115 if cls is Awaitable:
Guido van Rossum97c1adf2016-08-18 09:22:23 -0700116 return _check_methods(C, "__await__")
Yury Selivanov56fc6142015-05-29 09:01:29 -0400117 return NotImplemented
118
Guido van Rossum48b069a2020-04-07 09:50:06 -0700119 __class_getitem__ = classmethod(GenericAlias)
120
Yury Selivanov56fc6142015-05-29 09:01:29 -0400121
122class Coroutine(Awaitable):
Yury Selivanov75445082015-05-11 22:57:16 -0400123
124 __slots__ = ()
125
126 @abstractmethod
127 def send(self, value):
128 """Send a value into the coroutine.
129 Return next yielded value or raise StopIteration.
130 """
131 raise StopIteration
132
133 @abstractmethod
134 def throw(self, typ, val=None, tb=None):
135 """Raise an exception in the coroutine.
136 Return next yielded value or raise StopIteration.
137 """
138 if val is None:
139 if tb is None:
140 raise typ
141 val = typ()
142 if tb is not None:
143 val = val.with_traceback(tb)
144 raise val
145
146 def close(self):
147 """Raise GeneratorExit inside coroutine.
148 """
149 try:
150 self.throw(GeneratorExit)
151 except (GeneratorExit, StopIteration):
152 pass
153 else:
154 raise RuntimeError("coroutine ignored GeneratorExit")
155
Yury Selivanov75445082015-05-11 22:57:16 -0400156 @classmethod
157 def __subclasshook__(cls, C):
Yury Selivanov56fc6142015-05-29 09:01:29 -0400158 if cls is Coroutine:
Guido van Rossum97c1adf2016-08-18 09:22:23 -0700159 return _check_methods(C, '__await__', 'send', 'throw', 'close')
Yury Selivanov75445082015-05-11 22:57:16 -0400160 return NotImplemented
161
Yury Selivanov75445082015-05-11 22:57:16 -0400162
Yury Selivanov5376ba92015-06-22 12:19:30 -0400163Coroutine.register(coroutine)
164
165
Yury Selivanove0104ae2015-05-14 12:19:16 -0400166class AsyncIterable(metaclass=ABCMeta):
167
168 __slots__ = ()
169
170 @abstractmethod
Yury Selivanova6f6edb2016-06-09 15:08:31 -0400171 def __aiter__(self):
Yury Selivanove0104ae2015-05-14 12:19:16 -0400172 return AsyncIterator()
173
174 @classmethod
175 def __subclasshook__(cls, C):
176 if cls is AsyncIterable:
Guido van Rossum97c1adf2016-08-18 09:22:23 -0700177 return _check_methods(C, "__aiter__")
Yury Selivanove0104ae2015-05-14 12:19:16 -0400178 return NotImplemented
179
Guido van Rossum48b069a2020-04-07 09:50:06 -0700180 __class_getitem__ = classmethod(GenericAlias)
181
Yury Selivanove0104ae2015-05-14 12:19:16 -0400182
183class AsyncIterator(AsyncIterable):
184
185 __slots__ = ()
186
187 @abstractmethod
188 async def __anext__(self):
189 """Return the next item or raise StopAsyncIteration when exhausted."""
190 raise StopAsyncIteration
191
Yury Selivanova6f6edb2016-06-09 15:08:31 -0400192 def __aiter__(self):
Yury Selivanove0104ae2015-05-14 12:19:16 -0400193 return self
194
195 @classmethod
196 def __subclasshook__(cls, C):
197 if cls is AsyncIterator:
Guido van Rossum97c1adf2016-08-18 09:22:23 -0700198 return _check_methods(C, "__anext__", "__aiter__")
Yury Selivanove0104ae2015-05-14 12:19:16 -0400199 return NotImplemented
200
201
Yury Selivanov22214ab2016-11-16 18:25:04 -0500202class AsyncGenerator(AsyncIterator):
203
204 __slots__ = ()
205
206 async def __anext__(self):
207 """Return the next item from the asynchronous generator.
208 When exhausted, raise StopAsyncIteration.
209 """
210 return await self.asend(None)
211
212 @abstractmethod
213 async def asend(self, value):
214 """Send a value into the asynchronous generator.
215 Return next yielded value or raise StopAsyncIteration.
216 """
217 raise StopAsyncIteration
218
219 @abstractmethod
220 async def athrow(self, typ, val=None, tb=None):
221 """Raise an exception in the asynchronous generator.
222 Return next yielded value or raise StopAsyncIteration.
223 """
224 if val is None:
225 if tb is None:
226 raise typ
227 val = typ()
228 if tb is not None:
229 val = val.with_traceback(tb)
230 raise val
231
232 async def aclose(self):
233 """Raise GeneratorExit inside coroutine.
234 """
235 try:
236 await self.athrow(GeneratorExit)
237 except (GeneratorExit, StopAsyncIteration):
238 pass
239 else:
240 raise RuntimeError("asynchronous generator ignored GeneratorExit")
241
242 @classmethod
243 def __subclasshook__(cls, C):
244 if cls is AsyncGenerator:
245 return _check_methods(C, '__aiter__', '__anext__',
246 'asend', 'athrow', 'aclose')
247 return NotImplemented
248
249
250AsyncGenerator.register(async_generator)
251
252
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000253class Iterable(metaclass=ABCMeta):
254
Raymond Hettingerc46759a2011-03-22 11:46:25 -0700255 __slots__ = ()
256
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000257 @abstractmethod
258 def __iter__(self):
259 while False:
260 yield None
261
262 @classmethod
263 def __subclasshook__(cls, C):
264 if cls is Iterable:
Guido van Rossum97c1adf2016-08-18 09:22:23 -0700265 return _check_methods(C, "__iter__")
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000266 return NotImplemented
267
Guido van Rossum48b069a2020-04-07 09:50:06 -0700268 __class_getitem__ = classmethod(GenericAlias)
269
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000270
Raymond Hettinger74b64952008-02-09 02:53:48 +0000271class Iterator(Iterable):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000272
Raymond Hettingerc46759a2011-03-22 11:46:25 -0700273 __slots__ = ()
274
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000275 @abstractmethod
276 def __next__(self):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700277 'Return the next item from the iterator. When exhausted, raise StopIteration'
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000278 raise StopIteration
279
280 def __iter__(self):
281 return self
282
283 @classmethod
284 def __subclasshook__(cls, C):
285 if cls is Iterator:
Guido van Rossum97c1adf2016-08-18 09:22:23 -0700286 return _check_methods(C, '__iter__', '__next__')
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000287 return NotImplemented
288
Guido van Rossum48b069a2020-04-07 09:50:06 -0700289
Christian Heimesf83be4e2007-11-28 09:44:38 +0000290Iterator.register(bytes_iterator)
291Iterator.register(bytearray_iterator)
292#Iterator.register(callable_iterator)
293Iterator.register(dict_keyiterator)
294Iterator.register(dict_valueiterator)
295Iterator.register(dict_itemiterator)
296Iterator.register(list_iterator)
297Iterator.register(list_reverseiterator)
298Iterator.register(range_iterator)
Serhiy Storchaka48b1c3f2016-10-08 22:04:12 +0300299Iterator.register(longrange_iterator)
Christian Heimesf83be4e2007-11-28 09:44:38 +0000300Iterator.register(set_iterator)
301Iterator.register(str_iterator)
302Iterator.register(tuple_iterator)
303Iterator.register(zip_iterator)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000304
Raymond Hettingerbd60e8d2015-05-09 01:07:23 -0400305
Guido van Rossum16ca06b2016-04-04 10:59:29 -0700306class Reversible(Iterable):
307
308 __slots__ = ()
309
310 @abstractmethod
311 def __reversed__(self):
Guido van Rossum97c1adf2016-08-18 09:22:23 -0700312 while False:
313 yield None
Guido van Rossum16ca06b2016-04-04 10:59:29 -0700314
315 @classmethod
316 def __subclasshook__(cls, C):
317 if cls is Reversible:
Guido van Rossum97c1adf2016-08-18 09:22:23 -0700318 return _check_methods(C, "__reversed__", "__iter__")
Guido van Rossum16ca06b2016-04-04 10:59:29 -0700319 return NotImplemented
320
321
Raymond Hettingerbd60e8d2015-05-09 01:07:23 -0400322class Generator(Iterator):
323
324 __slots__ = ()
325
326 def __next__(self):
327 """Return the next item from the generator.
328 When exhausted, raise StopIteration.
329 """
330 return self.send(None)
331
332 @abstractmethod
333 def send(self, value):
334 """Send a value into the generator.
335 Return next yielded value or raise StopIteration.
336 """
337 raise StopIteration
338
339 @abstractmethod
340 def throw(self, typ, val=None, tb=None):
341 """Raise an exception in the generator.
342 Return next yielded value or raise StopIteration.
343 """
344 if val is None:
345 if tb is None:
346 raise typ
347 val = typ()
348 if tb is not None:
349 val = val.with_traceback(tb)
350 raise val
351
352 def close(self):
353 """Raise GeneratorExit inside generator.
354 """
355 try:
356 self.throw(GeneratorExit)
357 except (GeneratorExit, StopIteration):
358 pass
359 else:
360 raise RuntimeError("generator ignored GeneratorExit")
361
362 @classmethod
363 def __subclasshook__(cls, C):
364 if cls is Generator:
Guido van Rossum97c1adf2016-08-18 09:22:23 -0700365 return _check_methods(C, '__iter__', '__next__',
366 'send', 'throw', 'close')
Raymond Hettingerbd60e8d2015-05-09 01:07:23 -0400367 return NotImplemented
368
Guido van Rossum48b069a2020-04-07 09:50:06 -0700369
Raymond Hettingerbd60e8d2015-05-09 01:07:23 -0400370Generator.register(generator)
371
372
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000373class Sized(metaclass=ABCMeta):
374
Raymond Hettingerc46759a2011-03-22 11:46:25 -0700375 __slots__ = ()
376
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000377 @abstractmethod
378 def __len__(self):
379 return 0
380
381 @classmethod
382 def __subclasshook__(cls, C):
383 if cls is Sized:
Guido van Rossum97c1adf2016-08-18 09:22:23 -0700384 return _check_methods(C, "__len__")
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000385 return NotImplemented
386
387
388class Container(metaclass=ABCMeta):
389
Raymond Hettingerc46759a2011-03-22 11:46:25 -0700390 __slots__ = ()
391
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000392 @abstractmethod
393 def __contains__(self, x):
394 return False
395
396 @classmethod
397 def __subclasshook__(cls, C):
398 if cls is Container:
Guido van Rossum97c1adf2016-08-18 09:22:23 -0700399 return _check_methods(C, "__contains__")
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000400 return NotImplemented
401
Guido van Rossum48b069a2020-04-07 09:50:06 -0700402 __class_getitem__ = classmethod(GenericAlias)
403
404
Guido van Rossumf0666942016-08-23 10:47:07 -0700405class Collection(Sized, Iterable, Container):
406
407 __slots__ = ()
408
409 @classmethod
410 def __subclasshook__(cls, C):
411 if cls is Collection:
412 return _check_methods(C, "__len__", "__iter__", "__contains__")
413 return NotImplemented
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000414
Guido van Rossum48b069a2020-04-07 09:50:06 -0700415
kj463c7d32020-12-14 02:38:24 +0800416class _CallableGenericAlias(GenericAlias):
417 """ Represent `Callable[argtypes, resulttype]`.
418
kj73607be2020-12-24 12:33:48 +0800419 This sets ``__args__`` to a tuple containing the flattened ``argtypes``
kj463c7d32020-12-14 02:38:24 +0800420 followed by ``resulttype``.
421
422 Example: ``Callable[[int, str], float]`` sets ``__args__`` to
423 ``(int, str, float)``.
424 """
425
426 __slots__ = ()
427
428 def __new__(cls, origin, args):
429 return cls.__create_ga(origin, args)
430
431 @classmethod
432 def __create_ga(cls, origin, args):
433 if not isinstance(args, tuple) or len(args) != 2:
434 raise TypeError(
435 "Callable must be used as Callable[[arg, ...], result].")
436 t_args, t_result = args
kj6dd3da32020-12-24 10:47:40 +0800437 if isinstance(t_args, (list, tuple)):
kj463c7d32020-12-14 02:38:24 +0800438 ga_args = tuple(t_args) + (t_result,)
439 # This relaxes what t_args can be on purpose to allow things like
440 # PEP 612 ParamSpec. Responsibility for whether a user is using
441 # Callable[...] properly is deferred to static type checkers.
442 else:
443 ga_args = args
444 return super().__new__(cls, origin, ga_args)
445
446 def __repr__(self):
kj73607be2020-12-24 12:33:48 +0800447 if _has_special_args(self.__args__):
kj463c7d32020-12-14 02:38:24 +0800448 return super().__repr__()
449 return (f'collections.abc.Callable'
450 f'[[{", ".join([_type_repr(a) for a in self.__args__[:-1]])}], '
451 f'{_type_repr(self.__args__[-1])}]')
452
453 def __reduce__(self):
454 args = self.__args__
kj73607be2020-12-24 12:33:48 +0800455 if not _has_special_args(args):
kj463c7d32020-12-14 02:38:24 +0800456 args = list(args[:-1]), args[-1]
457 return _CallableGenericAlias, (Callable, args)
458
kj6dd3da32020-12-24 10:47:40 +0800459 def __getitem__(self, item):
460 # Called during TypeVar substitution, returns the custom subclass
461 # rather than the default types.GenericAlias object.
462 ga = super().__getitem__(item)
463 args = ga.__args__
kj73607be2020-12-24 12:33:48 +0800464 # args[0] occurs due to things like Z[[int, str, bool]] from PEP 612
465 if not isinstance(ga.__args__[0], tuple):
466 t_result = ga.__args__[-1]
467 t_args = ga.__args__[:-1]
468 args = (t_args, t_result)
kj6dd3da32020-12-24 10:47:40 +0800469 return _CallableGenericAlias(Callable, args)
470
kj463c7d32020-12-14 02:38:24 +0800471
kj73607be2020-12-24 12:33:48 +0800472def _has_special_args(args):
473 """Checks if args[0] matches either ``...``, ``ParamSpec`` or
474 ``_ConcatenateGenericAlias`` from typing.py
475 """
476 if len(args) != 2:
477 return False
478 obj = args[0]
479 if obj is Ellipsis:
480 return True
481 obj = type(obj)
482 names = ('ParamSpec', '_ConcatenateGenericAlias')
483 return obj.__module__ == 'typing' and any(obj.__name__ == name for name in names)
484
485
kj463c7d32020-12-14 02:38:24 +0800486def _type_repr(obj):
487 """Return the repr() of an object, special-casing types (internal helper).
488
489 Copied from :mod:`typing` since collections.abc
490 shouldn't depend on that module.
491 """
492 if isinstance(obj, GenericAlias):
493 return repr(obj)
494 if isinstance(obj, type):
495 if obj.__module__ == 'builtins':
496 return obj.__qualname__
497 return f'{obj.__module__}.{obj.__qualname__}'
498 if obj is Ellipsis:
499 return '...'
500 if isinstance(obj, FunctionType):
501 return obj.__name__
502 return repr(obj)
503
504
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000505class Callable(metaclass=ABCMeta):
506
Raymond Hettingerc46759a2011-03-22 11:46:25 -0700507 __slots__ = ()
508
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000509 @abstractmethod
Christian Heimes78644762008-03-04 23:39:23 +0000510 def __call__(self, *args, **kwds):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000511 return False
512
513 @classmethod
514 def __subclasshook__(cls, C):
515 if cls is Callable:
Guido van Rossum97c1adf2016-08-18 09:22:23 -0700516 return _check_methods(C, "__call__")
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000517 return NotImplemented
518
kj463c7d32020-12-14 02:38:24 +0800519 __class_getitem__ = classmethod(_CallableGenericAlias)
Guido van Rossum48b069a2020-04-07 09:50:06 -0700520
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000521
522### SETS ###
523
524
Guido van Rossumf0666942016-08-23 10:47:07 -0700525class Set(Collection):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000526 """A set is a finite, iterable container.
527
528 This class provides concrete generic implementations of all
529 methods except for __contains__, __iter__ and __len__.
530
531 To override the comparisons (presumably for speed, as the
Raymond Hettinger11cda472014-07-03 00:31:30 +0100532 semantics are fixed), redefine __le__ and __ge__,
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000533 then the other operations will automatically follow suit.
534 """
535
Raymond Hettingerc46759a2011-03-22 11:46:25 -0700536 __slots__ = ()
537
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000538 def __le__(self, other):
539 if not isinstance(other, Set):
540 return NotImplemented
541 if len(self) > len(other):
542 return False
543 for elem in self:
544 if elem not in other:
545 return False
546 return True
547
548 def __lt__(self, other):
549 if not isinstance(other, Set):
550 return NotImplemented
551 return len(self) < len(other) and self.__le__(other)
552
Raymond Hettinger71909422008-02-09 00:08:16 +0000553 def __gt__(self, other):
554 if not isinstance(other, Set):
555 return NotImplemented
Raymond Hettingerdd5e53a2014-05-26 00:09:04 -0700556 return len(self) > len(other) and self.__ge__(other)
Raymond Hettinger71909422008-02-09 00:08:16 +0000557
558 def __ge__(self, other):
559 if not isinstance(other, Set):
560 return NotImplemented
Raymond Hettingerdd5e53a2014-05-26 00:09:04 -0700561 if len(self) < len(other):
562 return False
563 for elem in other:
564 if elem not in self:
565 return False
566 return True
Raymond Hettinger71909422008-02-09 00:08:16 +0000567
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000568 def __eq__(self, other):
569 if not isinstance(other, Set):
570 return NotImplemented
571 return len(self) == len(other) and self.__le__(other)
572
573 @classmethod
574 def _from_iterable(cls, it):
Raymond Hettinger8284c4a2008-02-06 20:47:09 +0000575 '''Construct an instance of the class from any iterable input.
576
577 Must override this method if the class constructor signature
Raymond Hettinger7aebb642008-02-09 03:25:08 +0000578 does not accept an iterable for an input.
Raymond Hettinger8284c4a2008-02-06 20:47:09 +0000579 '''
Raymond Hettinger7aebb642008-02-09 03:25:08 +0000580 return cls(it)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000581
582 def __and__(self, other):
583 if not isinstance(other, Iterable):
584 return NotImplemented
585 return self._from_iterable(value for value in other if value in self)
586
Raymond Hettingerdd5e53a2014-05-26 00:09:04 -0700587 __rand__ = __and__
588
Christian Heimes190d79e2008-01-30 11:58:22 +0000589 def isdisjoint(self, other):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700590 'Return True if two sets have a null intersection.'
Christian Heimes190d79e2008-01-30 11:58:22 +0000591 for value in other:
592 if value in self:
593 return False
594 return True
595
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000596 def __or__(self, other):
597 if not isinstance(other, Iterable):
598 return NotImplemented
Christian Heimes78644762008-03-04 23:39:23 +0000599 chain = (e for s in (self, other) for e in s)
600 return self._from_iterable(chain)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000601
Raymond Hettingerdd5e53a2014-05-26 00:09:04 -0700602 __ror__ = __or__
603
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000604 def __sub__(self, other):
605 if not isinstance(other, Set):
606 if not isinstance(other, Iterable):
607 return NotImplemented
608 other = self._from_iterable(other)
609 return self._from_iterable(value for value in self
610 if value not in other)
611
Raymond Hettingerdd5e53a2014-05-26 00:09:04 -0700612 def __rsub__(self, other):
613 if not isinstance(other, Set):
614 if not isinstance(other, Iterable):
615 return NotImplemented
616 other = self._from_iterable(other)
617 return self._from_iterable(value for value in other
618 if value not in self)
619
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000620 def __xor__(self, other):
621 if not isinstance(other, Set):
622 if not isinstance(other, Iterable):
623 return NotImplemented
624 other = self._from_iterable(other)
625 return (self - other) | (other - self)
626
Raymond Hettingerdd5e53a2014-05-26 00:09:04 -0700627 __rxor__ = __xor__
628
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000629 def _hash(self):
630 """Compute the hash value of a set.
631
632 Note that we don't define __hash__: not all sets are hashable.
633 But if you define a hashable set type, its __hash__ should
634 call this function.
635
636 This must be compatible __eq__.
637
638 All sets ought to compare equal if they contain the same
639 elements, regardless of how they are implemented, and
640 regardless of the order of the elements; so there's not much
641 freedom for __eq__ or __hash__. We match the algorithm used
642 by the built-in frozenset type.
643 """
Christian Heimesa37d4c62007-12-04 23:02:19 +0000644 MAX = sys.maxsize
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000645 MASK = 2 * MAX + 1
646 n = len(self)
647 h = 1927868237 * (n + 1)
648 h &= MASK
649 for x in self:
650 hx = hash(x)
651 h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167
652 h &= MASK
653 h = h * 69069 + 907133923
654 h &= MASK
655 if h > MAX:
656 h -= MASK + 1
657 if h == -1:
658 h = 590923713
659 return h
660
Guido van Rossum48b069a2020-04-07 09:50:06 -0700661
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000662Set.register(frozenset)
663
664
665class MutableSet(Set):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700666 """A mutable set is a finite, iterable container.
667
668 This class provides concrete generic implementations of all
669 methods except for __contains__, __iter__, __len__,
670 add(), and discard().
671
672 To override the comparisons (presumably for speed, as the
673 semantics are fixed), all you have to do is redefine __le__ and
674 then the other operations will automatically follow suit.
675 """
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000676
Raymond Hettingerc46759a2011-03-22 11:46:25 -0700677 __slots__ = ()
678
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000679 @abstractmethod
680 def add(self, value):
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000681 """Add an element."""
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000682 raise NotImplementedError
683
684 @abstractmethod
685 def discard(self, value):
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000686 """Remove an element. Do not raise an exception if absent."""
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000687 raise NotImplementedError
688
Christian Heimes190d79e2008-01-30 11:58:22 +0000689 def remove(self, value):
690 """Remove an element. If not a member, raise a KeyError."""
691 if value not in self:
692 raise KeyError(value)
693 self.discard(value)
694
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000695 def pop(self):
696 """Return the popped value. Raise KeyError if empty."""
697 it = iter(self)
698 try:
Raymond Hettingerae650182009-01-28 23:33:59 +0000699 value = next(it)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000700 except StopIteration:
Serhiy Storchaka5affd232017-04-05 09:37:24 +0300701 raise KeyError from None
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000702 self.discard(value)
703 return value
704
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000705 def clear(self):
706 """This is slow (creates N new iterators!) but effective."""
707 try:
708 while True:
709 self.pop()
710 except KeyError:
711 pass
712
Raymond Hettingerb3d89a42011-01-12 20:37:47 +0000713 def __ior__(self, it):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000714 for value in it:
715 self.add(value)
716 return self
717
Raymond Hettingerb3d89a42011-01-12 20:37:47 +0000718 def __iand__(self, it):
Raymond Hettinger3f10a952009-04-01 19:05:50 +0000719 for value in (self - it):
720 self.discard(value)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000721 return self
722
Raymond Hettingerb3d89a42011-01-12 20:37:47 +0000723 def __ixor__(self, it):
Daniel Stutzbach31da5b22010-08-24 20:49:57 +0000724 if it is self:
725 self.clear()
726 else:
727 if not isinstance(it, Set):
728 it = self._from_iterable(it)
729 for value in it:
730 if value in self:
731 self.discard(value)
732 else:
733 self.add(value)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000734 return self
735
Raymond Hettingerb3d89a42011-01-12 20:37:47 +0000736 def __isub__(self, it):
Daniel Stutzbach31da5b22010-08-24 20:49:57 +0000737 if it is self:
738 self.clear()
739 else:
740 for value in it:
741 self.discard(value)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000742 return self
743
Guido van Rossum48b069a2020-04-07 09:50:06 -0700744
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000745MutableSet.register(set)
746
747
748### MAPPINGS ###
749
750
Guido van Rossumf0666942016-08-23 10:47:07 -0700751class Mapping(Collection):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700752 """A Mapping is a generic container for associating key/value
753 pairs.
754
755 This class provides concrete generic implementations of all
756 methods except for __getitem__, __iter__, and __len__.
Raymond Hettinger153866e2013-03-24 15:20:29 -0700757 """
758
Julien Palard282282a2020-11-17 22:50:23 +0100759 __slots__ = ()
760
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000761 @abstractmethod
762 def __getitem__(self, key):
763 raise KeyError
764
765 def get(self, key, default=None):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700766 'D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.'
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000767 try:
768 return self[key]
769 except KeyError:
770 return default
771
772 def __contains__(self, key):
773 try:
774 self[key]
775 except KeyError:
776 return False
777 else:
778 return True
779
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000780 def keys(self):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700781 "D.keys() -> a set-like object providing a view on D's keys"
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000782 return KeysView(self)
783
784 def items(self):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700785 "D.items() -> a set-like object providing a view on D's items"
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000786 return ItemsView(self)
787
788 def values(self):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700789 "D.values() -> an object providing a view on D's values"
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000790 return ValuesView(self)
791
Raymond Hettingerb9da9bc2008-02-04 20:44:31 +0000792 def __eq__(self, other):
Benjamin Peterson4ad6bd52010-05-21 20:55:22 +0000793 if not isinstance(other, Mapping):
794 return NotImplemented
795 return dict(self.items()) == dict(other.items())
Raymond Hettingerb9da9bc2008-02-04 20:44:31 +0000796
Guido van Rossum97c1adf2016-08-18 09:22:23 -0700797 __reversed__ = None
798
Guido van Rossum48b069a2020-04-07 09:50:06 -0700799
Victor Stinner7b17a4e2012-04-20 01:41:36 +0200800Mapping.register(mappingproxy)
801
Christian Heimes2202f872008-02-06 14:31:34 +0000802
Raymond Hettingerbfd06122008-02-09 10:04:32 +0000803class MappingView(Sized):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000804
Raymond Hettinger3170d1c2014-05-03 19:06:32 -0700805 __slots__ = '_mapping',
806
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000807 def __init__(self, mapping):
808 self._mapping = mapping
809
810 def __len__(self):
811 return len(self._mapping)
812
Raymond Hettinger89fc2b72009-02-27 07:47:32 +0000813 def __repr__(self):
814 return '{0.__class__.__name__}({0._mapping!r})'.format(self)
815
Guido van Rossum48b069a2020-04-07 09:50:06 -0700816 __class_getitem__ = classmethod(GenericAlias)
817
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000818
819class KeysView(MappingView, Set):
820
Raymond Hettinger3170d1c2014-05-03 19:06:32 -0700821 __slots__ = ()
822
Raymond Hettinger9117c752010-08-22 07:44:24 +0000823 @classmethod
824 def _from_iterable(self, it):
825 return set(it)
826
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000827 def __contains__(self, key):
828 return key in self._mapping
829
830 def __iter__(self):
Philip Jenvey4993cc02012-10-01 12:53:43 -0700831 yield from self._mapping
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000832
Guido van Rossum48b069a2020-04-07 09:50:06 -0700833
Christian Heimesf83be4e2007-11-28 09:44:38 +0000834KeysView.register(dict_keys)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000835
836
837class ItemsView(MappingView, Set):
838
Raymond Hettinger3170d1c2014-05-03 19:06:32 -0700839 __slots__ = ()
840
Raymond Hettinger9117c752010-08-22 07:44:24 +0000841 @classmethod
842 def _from_iterable(self, it):
843 return set(it)
844
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000845 def __contains__(self, item):
846 key, value = item
847 try:
848 v = self._mapping[key]
849 except KeyError:
850 return False
851 else:
Raymond Hettinger584e8ae2016-05-05 11:14:06 +0300852 return v is value or v == value
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000853
854 def __iter__(self):
855 for key in self._mapping:
856 yield (key, self._mapping[key])
857
Guido van Rossum48b069a2020-04-07 09:50:06 -0700858
Christian Heimesf83be4e2007-11-28 09:44:38 +0000859ItemsView.register(dict_items)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000860
861
Raymond Hettinger02556fb2018-01-11 21:53:49 -0800862class ValuesView(MappingView, Collection):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000863
Raymond Hettinger3170d1c2014-05-03 19:06:32 -0700864 __slots__ = ()
865
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000866 def __contains__(self, value):
867 for key in self._mapping:
Raymond Hettinger584e8ae2016-05-05 11:14:06 +0300868 v = self._mapping[key]
869 if v is value or v == value:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000870 return True
871 return False
872
873 def __iter__(self):
874 for key in self._mapping:
875 yield self._mapping[key]
876
Guido van Rossum48b069a2020-04-07 09:50:06 -0700877
Christian Heimesf83be4e2007-11-28 09:44:38 +0000878ValuesView.register(dict_values)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000879
880
881class MutableMapping(Mapping):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700882 """A MutableMapping is a generic container for associating
883 key/value pairs.
884
885 This class provides concrete generic implementations of all
886 methods except for __getitem__, __setitem__, __delitem__,
887 __iter__, and __len__.
Raymond Hettinger153866e2013-03-24 15:20:29 -0700888 """
889
Julien Palard282282a2020-11-17 22:50:23 +0100890 __slots__ = ()
891
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000892 @abstractmethod
893 def __setitem__(self, key, value):
894 raise KeyError
895
896 @abstractmethod
897 def __delitem__(self, key):
898 raise KeyError
899
900 __marker = object()
901
902 def pop(self, key, default=__marker):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700903 '''D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
904 If key is not found, d is returned if given, otherwise KeyError is raised.
905 '''
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000906 try:
907 value = self[key]
908 except KeyError:
909 if default is self.__marker:
910 raise
911 return default
912 else:
913 del self[key]
914 return value
915
916 def popitem(self):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700917 '''D.popitem() -> (k, v), remove and return some (key, value) pair
918 as a 2-tuple; but raise KeyError if D is empty.
919 '''
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000920 try:
921 key = next(iter(self))
922 except StopIteration:
Serhiy Storchaka5affd232017-04-05 09:37:24 +0300923 raise KeyError from None
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000924 value = self[key]
925 del self[key]
926 return key, value
927
928 def clear(self):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700929 'D.clear() -> None. Remove all items from D.'
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000930 try:
931 while True:
932 self.popitem()
933 except KeyError:
934 pass
935
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300936 def update(self, other=(), /, **kwds):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700937 ''' D.update([E, ]**F) -> None. Update D from mapping/iterable E and F.
938 If E present and has a .keys() method, does: for k in E: D[k] = E[k]
939 If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
940 In either case, this is followed by: for k, v in F.items(): D[k] = v
941 '''
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300942 if isinstance(other, Mapping):
943 for key in other:
944 self[key] = other[key]
945 elif hasattr(other, "keys"):
946 for key in other.keys():
947 self[key] = other[key]
948 else:
949 for key, value in other:
950 self[key] = value
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000951 for key, value in kwds.items():
952 self[key] = value
953
Raymond Hettingerb9da9bc2008-02-04 20:44:31 +0000954 def setdefault(self, key, default=None):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700955 'D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D'
Raymond Hettingerb9da9bc2008-02-04 20:44:31 +0000956 try:
957 return self[key]
958 except KeyError:
959 self[key] = default
960 return default
961
Guido van Rossum48b069a2020-04-07 09:50:06 -0700962
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000963MutableMapping.register(dict)
964
965
966### SEQUENCES ###
967
968
Guido van Rossumf0666942016-08-23 10:47:07 -0700969class Sequence(Reversible, Collection):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000970 """All the operations on a read-only sequence.
971
972 Concrete subclasses must override __new__ or __init__,
973 __getitem__, and __len__.
974 """
975
Raymond Hettingerc46759a2011-03-22 11:46:25 -0700976 __slots__ = ()
977
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000978 @abstractmethod
979 def __getitem__(self, index):
980 raise IndexError
981
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000982 def __iter__(self):
983 i = 0
Raymond Hettinger71909422008-02-09 00:08:16 +0000984 try:
985 while True:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000986 v = self[i]
Raymond Hettinger71909422008-02-09 00:08:16 +0000987 yield v
988 i += 1
989 except IndexError:
990 return
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000991
992 def __contains__(self, value):
993 for v in self:
Raymond Hettinger584e8ae2016-05-05 11:14:06 +0300994 if v is value or v == value:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000995 return True
996 return False
997
998 def __reversed__(self):
999 for i in reversed(range(len(self))):
1000 yield self[i]
1001
Raymond Hettingerec219ba2015-05-22 19:29:22 -07001002 def index(self, value, start=0, stop=None):
1003 '''S.index(value, [start, [stop]]) -> integer -- return first index of value.
Raymond Hettinger153866e2013-03-24 15:20:29 -07001004 Raises ValueError if the value is not present.
Nitish Chandra5ce0a2a2017-12-12 15:52:30 +05301005
1006 Supporting start and stop arguments is optional, but
1007 recommended.
Raymond Hettinger153866e2013-03-24 15:20:29 -07001008 '''
Raymond Hettingerec219ba2015-05-22 19:29:22 -07001009 if start is not None and start < 0:
1010 start = max(len(self) + start, 0)
1011 if stop is not None and stop < 0:
1012 stop += len(self)
1013
1014 i = start
1015 while stop is None or i < stop:
1016 try:
Xiang Zhangd5d32492017-03-08 11:04:24 +08001017 v = self[i]
1018 if v is value or v == value:
Raymond Hettingerec219ba2015-05-22 19:29:22 -07001019 return i
1020 except IndexError:
1021 break
1022 i += 1
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001023 raise ValueError
1024
1025 def count(self, value):
Raymond Hettinger153866e2013-03-24 15:20:29 -07001026 'S.count(value) -> integer -- return number of occurrences of value'
Xiang Zhangd5d32492017-03-08 11:04:24 +08001027 return sum(1 for v in self if v is value or v == value)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001028
Guido van Rossum48b069a2020-04-07 09:50:06 -07001029
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001030Sequence.register(tuple)
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001031Sequence.register(str)
Raymond Hettinger9aa53c22009-02-24 11:25:35 +00001032Sequence.register(range)
Nick Coghlan45163cc2013-10-02 22:31:47 +10001033Sequence.register(memoryview)
Guido van Rossumd05eb002007-11-21 22:26:24 +00001034
1035
1036class ByteString(Sequence):
Guido van Rossumd05eb002007-11-21 22:26:24 +00001037 """This unifies bytes and bytearray.
1038
1039 XXX Should add all their methods.
1040 """
1041
Raymond Hettingerc46759a2011-03-22 11:46:25 -07001042 __slots__ = ()
1043
Guido van Rossumd05eb002007-11-21 22:26:24 +00001044ByteString.register(bytes)
1045ByteString.register(bytearray)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001046
1047
1048class MutableSequence(Sequence):
Guido van Rossum840c3102013-07-25 11:55:41 -07001049 """All the operations on a read-write sequence.
Raymond Hettinger153866e2013-03-24 15:20:29 -07001050
1051 Concrete subclasses must provide __new__ or __init__,
1052 __getitem__, __setitem__, __delitem__, __len__, and insert().
Raymond Hettinger153866e2013-03-24 15:20:29 -07001053 """
1054
Julien Palard282282a2020-11-17 22:50:23 +01001055 __slots__ = ()
1056
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001057 @abstractmethod
1058 def __setitem__(self, index, value):
1059 raise IndexError
1060
1061 @abstractmethod
1062 def __delitem__(self, index):
1063 raise IndexError
1064
1065 @abstractmethod
1066 def insert(self, index, value):
Raymond Hettinger153866e2013-03-24 15:20:29 -07001067 'S.insert(index, value) -- insert value before index'
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001068 raise IndexError
1069
1070 def append(self, value):
Raymond Hettinger153866e2013-03-24 15:20:29 -07001071 'S.append(value) -- append value to the end of the sequence'
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001072 self.insert(len(self), value)
1073
Eli Bendersky9479d1a2011-03-04 05:34:58 +00001074 def clear(self):
Raymond Hettinger153866e2013-03-24 15:20:29 -07001075 'S.clear() -> None -- remove all items from S'
Eli Bendersky9479d1a2011-03-04 05:34:58 +00001076 try:
1077 while True:
1078 self.pop()
1079 except IndexError:
1080 pass
1081
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001082 def reverse(self):
Raymond Hettinger153866e2013-03-24 15:20:29 -07001083 'S.reverse() -- reverse *IN PLACE*'
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001084 n = len(self)
1085 for i in range(n//2):
1086 self[i], self[n-i-1] = self[n-i-1], self[i]
1087
1088 def extend(self, values):
Raymond Hettinger153866e2013-03-24 15:20:29 -07001089 'S.extend(iterable) -- extend sequence by appending elements from the iterable'
Naris R1b5f9c92018-08-31 02:56:14 +10001090 if values is self:
1091 values = list(values)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001092 for v in values:
1093 self.append(v)
1094
1095 def pop(self, index=-1):
Raymond Hettinger153866e2013-03-24 15:20:29 -07001096 '''S.pop([index]) -> item -- remove and return item at index (default last).
1097 Raise IndexError if list is empty or index is out of range.
1098 '''
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001099 v = self[index]
1100 del self[index]
1101 return v
1102
1103 def remove(self, value):
Raymond Hettinger153866e2013-03-24 15:20:29 -07001104 '''S.remove(value) -- remove first occurrence of value.
1105 Raise ValueError if the value is not present.
1106 '''
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001107 del self[self.index(value)]
1108
1109 def __iadd__(self, values):
1110 self.extend(values)
Raymond Hettingerc384b222009-05-18 15:35:26 +00001111 return self
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001112
Guido van Rossum48b069a2020-04-07 09:50:06 -07001113
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001114MutableSequence.register(list)
Guido van Rossumd05eb002007-11-21 22:26:24 +00001115MutableSequence.register(bytearray) # Multiply inheriting, see ByteString