blob: 7c3faa64ea7f981d93742f536de077311c587047 [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
419 This sets ``__args__`` to a tuple containing the flattened``argtypes``
420 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
437 if isinstance(t_args, list):
438 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):
447 if len(self.__args__) == 2 and self.__args__[0] is Ellipsis:
448 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__
455 if not (len(args) == 2 and args[0] is Ellipsis):
456 args = list(args[:-1]), args[-1]
457 return _CallableGenericAlias, (Callable, args)
458
459
460def _type_repr(obj):
461 """Return the repr() of an object, special-casing types (internal helper).
462
463 Copied from :mod:`typing` since collections.abc
464 shouldn't depend on that module.
465 """
466 if isinstance(obj, GenericAlias):
467 return repr(obj)
468 if isinstance(obj, type):
469 if obj.__module__ == 'builtins':
470 return obj.__qualname__
471 return f'{obj.__module__}.{obj.__qualname__}'
472 if obj is Ellipsis:
473 return '...'
474 if isinstance(obj, FunctionType):
475 return obj.__name__
476 return repr(obj)
477
478
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000479class Callable(metaclass=ABCMeta):
480
Raymond Hettingerc46759a2011-03-22 11:46:25 -0700481 __slots__ = ()
482
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000483 @abstractmethod
Christian Heimes78644762008-03-04 23:39:23 +0000484 def __call__(self, *args, **kwds):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000485 return False
486
487 @classmethod
488 def __subclasshook__(cls, C):
489 if cls is Callable:
Guido van Rossum97c1adf2016-08-18 09:22:23 -0700490 return _check_methods(C, "__call__")
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000491 return NotImplemented
492
kj463c7d32020-12-14 02:38:24 +0800493 __class_getitem__ = classmethod(_CallableGenericAlias)
Guido van Rossum48b069a2020-04-07 09:50:06 -0700494
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000495
496### SETS ###
497
498
Guido van Rossumf0666942016-08-23 10:47:07 -0700499class Set(Collection):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000500 """A set is a finite, iterable container.
501
502 This class provides concrete generic implementations of all
503 methods except for __contains__, __iter__ and __len__.
504
505 To override the comparisons (presumably for speed, as the
Raymond Hettinger11cda472014-07-03 00:31:30 +0100506 semantics are fixed), redefine __le__ and __ge__,
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000507 then the other operations will automatically follow suit.
508 """
509
Raymond Hettingerc46759a2011-03-22 11:46:25 -0700510 __slots__ = ()
511
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000512 def __le__(self, other):
513 if not isinstance(other, Set):
514 return NotImplemented
515 if len(self) > len(other):
516 return False
517 for elem in self:
518 if elem not in other:
519 return False
520 return True
521
522 def __lt__(self, other):
523 if not isinstance(other, Set):
524 return NotImplemented
525 return len(self) < len(other) and self.__le__(other)
526
Raymond Hettinger71909422008-02-09 00:08:16 +0000527 def __gt__(self, other):
528 if not isinstance(other, Set):
529 return NotImplemented
Raymond Hettingerdd5e53a2014-05-26 00:09:04 -0700530 return len(self) > len(other) and self.__ge__(other)
Raymond Hettinger71909422008-02-09 00:08:16 +0000531
532 def __ge__(self, other):
533 if not isinstance(other, Set):
534 return NotImplemented
Raymond Hettingerdd5e53a2014-05-26 00:09:04 -0700535 if len(self) < len(other):
536 return False
537 for elem in other:
538 if elem not in self:
539 return False
540 return True
Raymond Hettinger71909422008-02-09 00:08:16 +0000541
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000542 def __eq__(self, other):
543 if not isinstance(other, Set):
544 return NotImplemented
545 return len(self) == len(other) and self.__le__(other)
546
547 @classmethod
548 def _from_iterable(cls, it):
Raymond Hettinger8284c4a2008-02-06 20:47:09 +0000549 '''Construct an instance of the class from any iterable input.
550
551 Must override this method if the class constructor signature
Raymond Hettinger7aebb642008-02-09 03:25:08 +0000552 does not accept an iterable for an input.
Raymond Hettinger8284c4a2008-02-06 20:47:09 +0000553 '''
Raymond Hettinger7aebb642008-02-09 03:25:08 +0000554 return cls(it)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000555
556 def __and__(self, other):
557 if not isinstance(other, Iterable):
558 return NotImplemented
559 return self._from_iterable(value for value in other if value in self)
560
Raymond Hettingerdd5e53a2014-05-26 00:09:04 -0700561 __rand__ = __and__
562
Christian Heimes190d79e2008-01-30 11:58:22 +0000563 def isdisjoint(self, other):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700564 'Return True if two sets have a null intersection.'
Christian Heimes190d79e2008-01-30 11:58:22 +0000565 for value in other:
566 if value in self:
567 return False
568 return True
569
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000570 def __or__(self, other):
571 if not isinstance(other, Iterable):
572 return NotImplemented
Christian Heimes78644762008-03-04 23:39:23 +0000573 chain = (e for s in (self, other) for e in s)
574 return self._from_iterable(chain)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000575
Raymond Hettingerdd5e53a2014-05-26 00:09:04 -0700576 __ror__ = __or__
577
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000578 def __sub__(self, other):
579 if not isinstance(other, Set):
580 if not isinstance(other, Iterable):
581 return NotImplemented
582 other = self._from_iterable(other)
583 return self._from_iterable(value for value in self
584 if value not in other)
585
Raymond Hettingerdd5e53a2014-05-26 00:09:04 -0700586 def __rsub__(self, other):
587 if not isinstance(other, Set):
588 if not isinstance(other, Iterable):
589 return NotImplemented
590 other = self._from_iterable(other)
591 return self._from_iterable(value for value in other
592 if value not in self)
593
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000594 def __xor__(self, other):
595 if not isinstance(other, Set):
596 if not isinstance(other, Iterable):
597 return NotImplemented
598 other = self._from_iterable(other)
599 return (self - other) | (other - self)
600
Raymond Hettingerdd5e53a2014-05-26 00:09:04 -0700601 __rxor__ = __xor__
602
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000603 def _hash(self):
604 """Compute the hash value of a set.
605
606 Note that we don't define __hash__: not all sets are hashable.
607 But if you define a hashable set type, its __hash__ should
608 call this function.
609
610 This must be compatible __eq__.
611
612 All sets ought to compare equal if they contain the same
613 elements, regardless of how they are implemented, and
614 regardless of the order of the elements; so there's not much
615 freedom for __eq__ or __hash__. We match the algorithm used
616 by the built-in frozenset type.
617 """
Christian Heimesa37d4c62007-12-04 23:02:19 +0000618 MAX = sys.maxsize
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000619 MASK = 2 * MAX + 1
620 n = len(self)
621 h = 1927868237 * (n + 1)
622 h &= MASK
623 for x in self:
624 hx = hash(x)
625 h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167
626 h &= MASK
627 h = h * 69069 + 907133923
628 h &= MASK
629 if h > MAX:
630 h -= MASK + 1
631 if h == -1:
632 h = 590923713
633 return h
634
Guido van Rossum48b069a2020-04-07 09:50:06 -0700635
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000636Set.register(frozenset)
637
638
639class MutableSet(Set):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700640 """A mutable set is a finite, iterable container.
641
642 This class provides concrete generic implementations of all
643 methods except for __contains__, __iter__, __len__,
644 add(), and discard().
645
646 To override the comparisons (presumably for speed, as the
647 semantics are fixed), all you have to do is redefine __le__ and
648 then the other operations will automatically follow suit.
649 """
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000650
Raymond Hettingerc46759a2011-03-22 11:46:25 -0700651 __slots__ = ()
652
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000653 @abstractmethod
654 def add(self, value):
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000655 """Add an element."""
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000656 raise NotImplementedError
657
658 @abstractmethod
659 def discard(self, value):
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000660 """Remove an element. Do not raise an exception if absent."""
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000661 raise NotImplementedError
662
Christian Heimes190d79e2008-01-30 11:58:22 +0000663 def remove(self, value):
664 """Remove an element. If not a member, raise a KeyError."""
665 if value not in self:
666 raise KeyError(value)
667 self.discard(value)
668
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000669 def pop(self):
670 """Return the popped value. Raise KeyError if empty."""
671 it = iter(self)
672 try:
Raymond Hettingerae650182009-01-28 23:33:59 +0000673 value = next(it)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000674 except StopIteration:
Serhiy Storchaka5affd232017-04-05 09:37:24 +0300675 raise KeyError from None
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000676 self.discard(value)
677 return value
678
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000679 def clear(self):
680 """This is slow (creates N new iterators!) but effective."""
681 try:
682 while True:
683 self.pop()
684 except KeyError:
685 pass
686
Raymond Hettingerb3d89a42011-01-12 20:37:47 +0000687 def __ior__(self, it):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000688 for value in it:
689 self.add(value)
690 return self
691
Raymond Hettingerb3d89a42011-01-12 20:37:47 +0000692 def __iand__(self, it):
Raymond Hettinger3f10a952009-04-01 19:05:50 +0000693 for value in (self - it):
694 self.discard(value)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000695 return self
696
Raymond Hettingerb3d89a42011-01-12 20:37:47 +0000697 def __ixor__(self, it):
Daniel Stutzbach31da5b22010-08-24 20:49:57 +0000698 if it is self:
699 self.clear()
700 else:
701 if not isinstance(it, Set):
702 it = self._from_iterable(it)
703 for value in it:
704 if value in self:
705 self.discard(value)
706 else:
707 self.add(value)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000708 return self
709
Raymond Hettingerb3d89a42011-01-12 20:37:47 +0000710 def __isub__(self, it):
Daniel Stutzbach31da5b22010-08-24 20:49:57 +0000711 if it is self:
712 self.clear()
713 else:
714 for value in it:
715 self.discard(value)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000716 return self
717
Guido van Rossum48b069a2020-04-07 09:50:06 -0700718
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000719MutableSet.register(set)
720
721
722### MAPPINGS ###
723
724
Guido van Rossumf0666942016-08-23 10:47:07 -0700725class Mapping(Collection):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700726 """A Mapping is a generic container for associating key/value
727 pairs.
728
729 This class provides concrete generic implementations of all
730 methods except for __getitem__, __iter__, and __len__.
Raymond Hettinger153866e2013-03-24 15:20:29 -0700731 """
732
Julien Palard282282a2020-11-17 22:50:23 +0100733 __slots__ = ()
734
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000735 @abstractmethod
736 def __getitem__(self, key):
737 raise KeyError
738
739 def get(self, key, default=None):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700740 'D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.'
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000741 try:
742 return self[key]
743 except KeyError:
744 return default
745
746 def __contains__(self, key):
747 try:
748 self[key]
749 except KeyError:
750 return False
751 else:
752 return True
753
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000754 def keys(self):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700755 "D.keys() -> a set-like object providing a view on D's keys"
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000756 return KeysView(self)
757
758 def items(self):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700759 "D.items() -> a set-like object providing a view on D's items"
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000760 return ItemsView(self)
761
762 def values(self):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700763 "D.values() -> an object providing a view on D's values"
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000764 return ValuesView(self)
765
Raymond Hettingerb9da9bc2008-02-04 20:44:31 +0000766 def __eq__(self, other):
Benjamin Peterson4ad6bd52010-05-21 20:55:22 +0000767 if not isinstance(other, Mapping):
768 return NotImplemented
769 return dict(self.items()) == dict(other.items())
Raymond Hettingerb9da9bc2008-02-04 20:44:31 +0000770
Guido van Rossum97c1adf2016-08-18 09:22:23 -0700771 __reversed__ = None
772
Guido van Rossum48b069a2020-04-07 09:50:06 -0700773
Victor Stinner7b17a4e2012-04-20 01:41:36 +0200774Mapping.register(mappingproxy)
775
Christian Heimes2202f872008-02-06 14:31:34 +0000776
Raymond Hettingerbfd06122008-02-09 10:04:32 +0000777class MappingView(Sized):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000778
Raymond Hettinger3170d1c2014-05-03 19:06:32 -0700779 __slots__ = '_mapping',
780
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000781 def __init__(self, mapping):
782 self._mapping = mapping
783
784 def __len__(self):
785 return len(self._mapping)
786
Raymond Hettinger89fc2b72009-02-27 07:47:32 +0000787 def __repr__(self):
788 return '{0.__class__.__name__}({0._mapping!r})'.format(self)
789
Guido van Rossum48b069a2020-04-07 09:50:06 -0700790 __class_getitem__ = classmethod(GenericAlias)
791
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000792
793class KeysView(MappingView, Set):
794
Raymond Hettinger3170d1c2014-05-03 19:06:32 -0700795 __slots__ = ()
796
Raymond Hettinger9117c752010-08-22 07:44:24 +0000797 @classmethod
798 def _from_iterable(self, it):
799 return set(it)
800
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000801 def __contains__(self, key):
802 return key in self._mapping
803
804 def __iter__(self):
Philip Jenvey4993cc02012-10-01 12:53:43 -0700805 yield from self._mapping
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000806
Guido van Rossum48b069a2020-04-07 09:50:06 -0700807
Christian Heimesf83be4e2007-11-28 09:44:38 +0000808KeysView.register(dict_keys)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000809
810
811class ItemsView(MappingView, Set):
812
Raymond Hettinger3170d1c2014-05-03 19:06:32 -0700813 __slots__ = ()
814
Raymond Hettinger9117c752010-08-22 07:44:24 +0000815 @classmethod
816 def _from_iterable(self, it):
817 return set(it)
818
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000819 def __contains__(self, item):
820 key, value = item
821 try:
822 v = self._mapping[key]
823 except KeyError:
824 return False
825 else:
Raymond Hettinger584e8ae2016-05-05 11:14:06 +0300826 return v is value or v == value
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000827
828 def __iter__(self):
829 for key in self._mapping:
830 yield (key, self._mapping[key])
831
Guido van Rossum48b069a2020-04-07 09:50:06 -0700832
Christian Heimesf83be4e2007-11-28 09:44:38 +0000833ItemsView.register(dict_items)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000834
835
Raymond Hettinger02556fb2018-01-11 21:53:49 -0800836class ValuesView(MappingView, Collection):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000837
Raymond Hettinger3170d1c2014-05-03 19:06:32 -0700838 __slots__ = ()
839
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000840 def __contains__(self, value):
841 for key in self._mapping:
Raymond Hettinger584e8ae2016-05-05 11:14:06 +0300842 v = self._mapping[key]
843 if v is value or v == value:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000844 return True
845 return False
846
847 def __iter__(self):
848 for key in self._mapping:
849 yield self._mapping[key]
850
Guido van Rossum48b069a2020-04-07 09:50:06 -0700851
Christian Heimesf83be4e2007-11-28 09:44:38 +0000852ValuesView.register(dict_values)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000853
854
855class MutableMapping(Mapping):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700856 """A MutableMapping is a generic container for associating
857 key/value pairs.
858
859 This class provides concrete generic implementations of all
860 methods except for __getitem__, __setitem__, __delitem__,
861 __iter__, and __len__.
Raymond Hettinger153866e2013-03-24 15:20:29 -0700862 """
863
Julien Palard282282a2020-11-17 22:50:23 +0100864 __slots__ = ()
865
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000866 @abstractmethod
867 def __setitem__(self, key, value):
868 raise KeyError
869
870 @abstractmethod
871 def __delitem__(self, key):
872 raise KeyError
873
874 __marker = object()
875
876 def pop(self, key, default=__marker):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700877 '''D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
878 If key is not found, d is returned if given, otherwise KeyError is raised.
879 '''
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000880 try:
881 value = self[key]
882 except KeyError:
883 if default is self.__marker:
884 raise
885 return default
886 else:
887 del self[key]
888 return value
889
890 def popitem(self):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700891 '''D.popitem() -> (k, v), remove and return some (key, value) pair
892 as a 2-tuple; but raise KeyError if D is empty.
893 '''
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000894 try:
895 key = next(iter(self))
896 except StopIteration:
Serhiy Storchaka5affd232017-04-05 09:37:24 +0300897 raise KeyError from None
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000898 value = self[key]
899 del self[key]
900 return key, value
901
902 def clear(self):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700903 'D.clear() -> None. Remove all items from D.'
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000904 try:
905 while True:
906 self.popitem()
907 except KeyError:
908 pass
909
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300910 def update(self, other=(), /, **kwds):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700911 ''' D.update([E, ]**F) -> None. Update D from mapping/iterable E and F.
912 If E present and has a .keys() method, does: for k in E: D[k] = E[k]
913 If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
914 In either case, this is followed by: for k, v in F.items(): D[k] = v
915 '''
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300916 if isinstance(other, Mapping):
917 for key in other:
918 self[key] = other[key]
919 elif hasattr(other, "keys"):
920 for key in other.keys():
921 self[key] = other[key]
922 else:
923 for key, value in other:
924 self[key] = value
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000925 for key, value in kwds.items():
926 self[key] = value
927
Raymond Hettingerb9da9bc2008-02-04 20:44:31 +0000928 def setdefault(self, key, default=None):
Raymond Hettinger153866e2013-03-24 15:20:29 -0700929 '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 +0000930 try:
931 return self[key]
932 except KeyError:
933 self[key] = default
934 return default
935
Guido van Rossum48b069a2020-04-07 09:50:06 -0700936
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000937MutableMapping.register(dict)
938
939
940### SEQUENCES ###
941
942
Guido van Rossumf0666942016-08-23 10:47:07 -0700943class Sequence(Reversible, Collection):
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000944 """All the operations on a read-only sequence.
945
946 Concrete subclasses must override __new__ or __init__,
947 __getitem__, and __len__.
948 """
949
Raymond Hettingerc46759a2011-03-22 11:46:25 -0700950 __slots__ = ()
951
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000952 @abstractmethod
953 def __getitem__(self, index):
954 raise IndexError
955
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000956 def __iter__(self):
957 i = 0
Raymond Hettinger71909422008-02-09 00:08:16 +0000958 try:
959 while True:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000960 v = self[i]
Raymond Hettinger71909422008-02-09 00:08:16 +0000961 yield v
962 i += 1
963 except IndexError:
964 return
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000965
966 def __contains__(self, value):
967 for v in self:
Raymond Hettinger584e8ae2016-05-05 11:14:06 +0300968 if v is value or v == value:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000969 return True
970 return False
971
972 def __reversed__(self):
973 for i in reversed(range(len(self))):
974 yield self[i]
975
Raymond Hettingerec219ba2015-05-22 19:29:22 -0700976 def index(self, value, start=0, stop=None):
977 '''S.index(value, [start, [stop]]) -> integer -- return first index of value.
Raymond Hettinger153866e2013-03-24 15:20:29 -0700978 Raises ValueError if the value is not present.
Nitish Chandra5ce0a2a2017-12-12 15:52:30 +0530979
980 Supporting start and stop arguments is optional, but
981 recommended.
Raymond Hettinger153866e2013-03-24 15:20:29 -0700982 '''
Raymond Hettingerec219ba2015-05-22 19:29:22 -0700983 if start is not None and start < 0:
984 start = max(len(self) + start, 0)
985 if stop is not None and stop < 0:
986 stop += len(self)
987
988 i = start
989 while stop is None or i < stop:
990 try:
Xiang Zhangd5d32492017-03-08 11:04:24 +0800991 v = self[i]
992 if v is value or v == value:
Raymond Hettingerec219ba2015-05-22 19:29:22 -0700993 return i
994 except IndexError:
995 break
996 i += 1
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000997 raise ValueError
998
999 def count(self, value):
Raymond Hettinger153866e2013-03-24 15:20:29 -07001000 'S.count(value) -> integer -- return number of occurrences of value'
Xiang Zhangd5d32492017-03-08 11:04:24 +08001001 return sum(1 for v in self if v is value or v == value)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001002
Guido van Rossum48b069a2020-04-07 09:50:06 -07001003
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001004Sequence.register(tuple)
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001005Sequence.register(str)
Raymond Hettinger9aa53c22009-02-24 11:25:35 +00001006Sequence.register(range)
Nick Coghlan45163cc2013-10-02 22:31:47 +10001007Sequence.register(memoryview)
Guido van Rossumd05eb002007-11-21 22:26:24 +00001008
1009
1010class ByteString(Sequence):
Guido van Rossumd05eb002007-11-21 22:26:24 +00001011 """This unifies bytes and bytearray.
1012
1013 XXX Should add all their methods.
1014 """
1015
Raymond Hettingerc46759a2011-03-22 11:46:25 -07001016 __slots__ = ()
1017
Guido van Rossumd05eb002007-11-21 22:26:24 +00001018ByteString.register(bytes)
1019ByteString.register(bytearray)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001020
1021
1022class MutableSequence(Sequence):
Guido van Rossum840c3102013-07-25 11:55:41 -07001023 """All the operations on a read-write sequence.
Raymond Hettinger153866e2013-03-24 15:20:29 -07001024
1025 Concrete subclasses must provide __new__ or __init__,
1026 __getitem__, __setitem__, __delitem__, __len__, and insert().
Raymond Hettinger153866e2013-03-24 15:20:29 -07001027 """
1028
Julien Palard282282a2020-11-17 22:50:23 +01001029 __slots__ = ()
1030
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001031 @abstractmethod
1032 def __setitem__(self, index, value):
1033 raise IndexError
1034
1035 @abstractmethod
1036 def __delitem__(self, index):
1037 raise IndexError
1038
1039 @abstractmethod
1040 def insert(self, index, value):
Raymond Hettinger153866e2013-03-24 15:20:29 -07001041 'S.insert(index, value) -- insert value before index'
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001042 raise IndexError
1043
1044 def append(self, value):
Raymond Hettinger153866e2013-03-24 15:20:29 -07001045 'S.append(value) -- append value to the end of the sequence'
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001046 self.insert(len(self), value)
1047
Eli Bendersky9479d1a2011-03-04 05:34:58 +00001048 def clear(self):
Raymond Hettinger153866e2013-03-24 15:20:29 -07001049 'S.clear() -> None -- remove all items from S'
Eli Bendersky9479d1a2011-03-04 05:34:58 +00001050 try:
1051 while True:
1052 self.pop()
1053 except IndexError:
1054 pass
1055
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001056 def reverse(self):
Raymond Hettinger153866e2013-03-24 15:20:29 -07001057 'S.reverse() -- reverse *IN PLACE*'
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001058 n = len(self)
1059 for i in range(n//2):
1060 self[i], self[n-i-1] = self[n-i-1], self[i]
1061
1062 def extend(self, values):
Raymond Hettinger153866e2013-03-24 15:20:29 -07001063 'S.extend(iterable) -- extend sequence by appending elements from the iterable'
Naris R1b5f9c92018-08-31 02:56:14 +10001064 if values is self:
1065 values = list(values)
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001066 for v in values:
1067 self.append(v)
1068
1069 def pop(self, index=-1):
Raymond Hettinger153866e2013-03-24 15:20:29 -07001070 '''S.pop([index]) -> item -- remove and return item at index (default last).
1071 Raise IndexError if list is empty or index is out of range.
1072 '''
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001073 v = self[index]
1074 del self[index]
1075 return v
1076
1077 def remove(self, value):
Raymond Hettinger153866e2013-03-24 15:20:29 -07001078 '''S.remove(value) -- remove first occurrence of value.
1079 Raise ValueError if the value is not present.
1080 '''
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001081 del self[self.index(value)]
1082
1083 def __iadd__(self, values):
1084 self.extend(values)
Raymond Hettingerc384b222009-05-18 15:35:26 +00001085 return self
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001086
Guido van Rossum48b069a2020-04-07 09:50:06 -07001087
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001088MutableSequence.register(list)
Guido van Rossumd05eb002007-11-21 22:26:24 +00001089MutableSequence.register(bytearray) # Multiply inheriting, see ByteString