1# 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 6Unit tests are in test_collections. 7""" 8 9from abc import ABCMeta, abstractmethod 10import sys 11 12GenericAlias = type(list[int]) 13EllipsisType = type(...) 14def _f(): pass 15FunctionType = type(_f) 16del _f 17 18__all__ = ["Awaitable", "Coroutine", 19 "AsyncIterable", "AsyncIterator", "AsyncGenerator", 20 "Hashable", "Iterable", "Iterator", "Generator", "Reversible", 21 "Sized", "Container", "Callable", "Collection", 22 "Set", "MutableSet", 23 "Mapping", "MutableMapping", 24 "MappingView", "KeysView", "ItemsView", "ValuesView", 25 "Sequence", "MutableSequence", 26 "ByteString", 27 ] 28 29# 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 35# 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) 39# Note: in other implementations, these types might not be distinct 40# and they may have their own implementation specific types that 41# are not included on this list. 42bytes_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))) 51longrange_iterator = type(iter(range(1 << 1000))) 52set_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()) 60## misc ## 61mappingproxy = type(type.__dict__) 62generator = type((lambda: (yield))()) 63## coroutine ## 64async def _coro(): pass 65_coro = _coro() 66coroutine = type(_coro) 67_coro.close() # Prevent ResourceWarning 68del _coro 69## asynchronous generator ## 70async def _ag(): yield 71_ag = _ag() 72async_generator = type(_ag) 73del _ag 74 75 76### ONE-TRICK PONIES ### 77 78def _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 90class Hashable(metaclass=ABCMeta): 91 92 __slots__ = () 93 94 @abstractmethod 95 def __hash__(self): 96 return 0 97 98 @classmethod 99 def __subclasshook__(cls, C): 100 if cls is Hashable: 101 return _check_methods(C, "__hash__") 102 return NotImplemented 103 104 105class Awaitable(metaclass=ABCMeta): 106 107 __slots__ = () 108 109 @abstractmethod 110 def __await__(self): 111 yield 112 113 @classmethod 114 def __subclasshook__(cls, C): 115 if cls is Awaitable: 116 return _check_methods(C, "__await__") 117 return NotImplemented 118 119 __class_getitem__ = classmethod(GenericAlias) 120 121 122class Coroutine(Awaitable): 123 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 156 @classmethod 157 def __subclasshook__(cls, C): 158 if cls is Coroutine: 159 return _check_methods(C, '__await__', 'send', 'throw', 'close') 160 return NotImplemented 161 162 163Coroutine.register(coroutine) 164 165 166class AsyncIterable(metaclass=ABCMeta): 167 168 __slots__ = () 169 170 @abstractmethod 171 def __aiter__(self): 172 return AsyncIterator() 173 174 @classmethod 175 def __subclasshook__(cls, C): 176 if cls is AsyncIterable: 177 return _check_methods(C, "__aiter__") 178 return NotImplemented 179 180 __class_getitem__ = classmethod(GenericAlias) 181 182 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 192 def __aiter__(self): 193 return self 194 195 @classmethod 196 def __subclasshook__(cls, C): 197 if cls is AsyncIterator: 198 return _check_methods(C, "__anext__", "__aiter__") 199 return NotImplemented 200 201 202class 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 253class Iterable(metaclass=ABCMeta): 254 255 __slots__ = () 256 257 @abstractmethod 258 def __iter__(self): 259 while False: 260 yield None 261 262 @classmethod 263 def __subclasshook__(cls, C): 264 if cls is Iterable: 265 return _check_methods(C, "__iter__") 266 return NotImplemented 267 268 __class_getitem__ = classmethod(GenericAlias) 269 270 271class Iterator(Iterable): 272 273 __slots__ = () 274 275 @abstractmethod 276 def __next__(self): 277 'Return the next item from the iterator. When exhausted, raise StopIteration' 278 raise StopIteration 279 280 def __iter__(self): 281 return self 282 283 @classmethod 284 def __subclasshook__(cls, C): 285 if cls is Iterator: 286 return _check_methods(C, '__iter__', '__next__') 287 return NotImplemented 288 289 290Iterator.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) 299Iterator.register(longrange_iterator) 300Iterator.register(set_iterator) 301Iterator.register(str_iterator) 302Iterator.register(tuple_iterator) 303Iterator.register(zip_iterator) 304 305 306class Reversible(Iterable): 307 308 __slots__ = () 309 310 @abstractmethod 311 def __reversed__(self): 312 while False: 313 yield None 314 315 @classmethod 316 def __subclasshook__(cls, C): 317 if cls is Reversible: 318 return _check_methods(C, "__reversed__", "__iter__") 319 return NotImplemented 320 321 322class 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: 365 return _check_methods(C, '__iter__', '__next__', 366 'send', 'throw', 'close') 367 return NotImplemented 368 369 370Generator.register(generator) 371 372 373class Sized(metaclass=ABCMeta): 374 375 __slots__ = () 376 377 @abstractmethod 378 def __len__(self): 379 return 0 380 381 @classmethod 382 def __subclasshook__(cls, C): 383 if cls is Sized: 384 return _check_methods(C, "__len__") 385 return NotImplemented 386 387 388class Container(metaclass=ABCMeta): 389 390 __slots__ = () 391 392 @abstractmethod 393 def __contains__(self, x): 394 return False 395 396 @classmethod 397 def __subclasshook__(cls, C): 398 if cls is Container: 399 return _check_methods(C, "__contains__") 400 return NotImplemented 401 402 __class_getitem__ = classmethod(GenericAlias) 403 404 405class 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 414 415 416class _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 try: 430 return cls.__create_ga(origin, args) 431 except TypeError as exc: 432 import warnings 433 warnings.warn(f'{str(exc)} ' 434 f'(This will raise a TypeError in Python 3.10.)', 435 DeprecationWarning) 436 return GenericAlias(origin, args) 437 438 @classmethod 439 def __create_ga(cls, origin, args): 440 if not isinstance(args, tuple) or len(args) != 2: 441 raise TypeError( 442 "Callable must be used as Callable[[arg, ...], result].") 443 t_args, t_result = args 444 if isinstance(t_args, (list, tuple)): 445 ga_args = tuple(t_args) + (t_result,) 446 # This relaxes what t_args can be on purpose to allow things like 447 # PEP 612 ParamSpec. Responsibility for whether a user is using 448 # Callable[...] properly is deferred to static type checkers. 449 else: 450 ga_args = args 451 return super().__new__(cls, origin, ga_args) 452 453 def __repr__(self): 454 if len(self.__args__) == 2 and self.__args__[0] is Ellipsis: 455 return super().__repr__() 456 return (f'collections.abc.Callable' 457 f'[[{", ".join([_type_repr(a) for a in self.__args__[:-1]])}], ' 458 f'{_type_repr(self.__args__[-1])}]') 459 460 def __reduce__(self): 461 args = self.__args__ 462 if not (len(args) == 2 and args[0] is Ellipsis): 463 args = list(args[:-1]), args[-1] 464 return _CallableGenericAlias, (Callable, args) 465 466 def __getitem__(self, item): 467 # Called during TypeVar substitution, returns the custom subclass 468 # rather than the default types.GenericAlias object. 469 ga = super().__getitem__(item) 470 args = ga.__args__ 471 t_result = args[-1] 472 t_args = args[:-1] 473 args = (t_args, t_result) 474 return _CallableGenericAlias(Callable, args) 475 476 477def _type_repr(obj): 478 """Return the repr() of an object, special-casing types (internal helper). 479 480 Copied from :mod:`typing` since collections.abc 481 shouldn't depend on that module. 482 """ 483 if isinstance(obj, GenericAlias): 484 return repr(obj) 485 if isinstance(obj, type): 486 if obj.__module__ == 'builtins': 487 return obj.__qualname__ 488 return f'{obj.__module__}.{obj.__qualname__}' 489 if obj is Ellipsis: 490 return '...' 491 if isinstance(obj, FunctionType): 492 return obj.__name__ 493 return repr(obj) 494 495 496class Callable(metaclass=ABCMeta): 497 498 __slots__ = () 499 500 @abstractmethod 501 def __call__(self, *args, **kwds): 502 return False 503 504 @classmethod 505 def __subclasshook__(cls, C): 506 if cls is Callable: 507 return _check_methods(C, "__call__") 508 return NotImplemented 509 510 __class_getitem__ = classmethod(_CallableGenericAlias) 511 512 513### SETS ### 514 515 516class Set(Collection): 517 518 """A set is a finite, iterable container. 519 520 This class provides concrete generic implementations of all 521 methods except for __contains__, __iter__ and __len__. 522 523 To override the comparisons (presumably for speed, as the 524 semantics are fixed), redefine __le__ and __ge__, 525 then the other operations will automatically follow suit. 526 """ 527 528 __slots__ = () 529 530 def __le__(self, other): 531 if not isinstance(other, Set): 532 return NotImplemented 533 if len(self) > len(other): 534 return False 535 for elem in self: 536 if elem not in other: 537 return False 538 return True 539 540 def __lt__(self, other): 541 if not isinstance(other, Set): 542 return NotImplemented 543 return len(self) < len(other) and self.__le__(other) 544 545 def __gt__(self, other): 546 if not isinstance(other, Set): 547 return NotImplemented 548 return len(self) > len(other) and self.__ge__(other) 549 550 def __ge__(self, other): 551 if not isinstance(other, Set): 552 return NotImplemented 553 if len(self) < len(other): 554 return False 555 for elem in other: 556 if elem not in self: 557 return False 558 return True 559 560 def __eq__(self, other): 561 if not isinstance(other, Set): 562 return NotImplemented 563 return len(self) == len(other) and self.__le__(other) 564 565 @classmethod 566 def _from_iterable(cls, it): 567 '''Construct an instance of the class from any iterable input. 568 569 Must override this method if the class constructor signature 570 does not accept an iterable for an input. 571 ''' 572 return cls(it) 573 574 def __and__(self, other): 575 if not isinstance(other, Iterable): 576 return NotImplemented 577 return self._from_iterable(value for value in other if value in self) 578 579 __rand__ = __and__ 580 581 def isdisjoint(self, other): 582 'Return True if two sets have a null intersection.' 583 for value in other: 584 if value in self: 585 return False 586 return True 587 588 def __or__(self, other): 589 if not isinstance(other, Iterable): 590 return NotImplemented 591 chain = (e for s in (self, other) for e in s) 592 return self._from_iterable(chain) 593 594 __ror__ = __or__ 595 596 def __sub__(self, other): 597 if not isinstance(other, Set): 598 if not isinstance(other, Iterable): 599 return NotImplemented 600 other = self._from_iterable(other) 601 return self._from_iterable(value for value in self 602 if value not in other) 603 604 def __rsub__(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 other 610 if value not in self) 611 612 def __xor__(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 - other) | (other - self) 618 619 __rxor__ = __xor__ 620 621 def _hash(self): 622 """Compute the hash value of a set. 623 624 Note that we don't define __hash__: not all sets are hashable. 625 But if you define a hashable set type, its __hash__ should 626 call this function. 627 628 This must be compatible __eq__. 629 630 All sets ought to compare equal if they contain the same 631 elements, regardless of how they are implemented, and 632 regardless of the order of the elements; so there's not much 633 freedom for __eq__ or __hash__. We match the algorithm used 634 by the built-in frozenset type. 635 """ 636 MAX = sys.maxsize 637 MASK = 2 * MAX + 1 638 n = len(self) 639 h = 1927868237 * (n + 1) 640 h &= MASK 641 for x in self: 642 hx = hash(x) 643 h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167 644 h &= MASK 645 h = h * 69069 + 907133923 646 h &= MASK 647 if h > MAX: 648 h -= MASK + 1 649 if h == -1: 650 h = 590923713 651 return h 652 653 654Set.register(frozenset) 655 656 657class MutableSet(Set): 658 """A mutable set is a finite, iterable container. 659 660 This class provides concrete generic implementations of all 661 methods except for __contains__, __iter__, __len__, 662 add(), and discard(). 663 664 To override the comparisons (presumably for speed, as the 665 semantics are fixed), all you have to do is redefine __le__ and 666 then the other operations will automatically follow suit. 667 """ 668 669 __slots__ = () 670 671 @abstractmethod 672 def add(self, value): 673 """Add an element.""" 674 raise NotImplementedError 675 676 @abstractmethod 677 def discard(self, value): 678 """Remove an element. Do not raise an exception if absent.""" 679 raise NotImplementedError 680 681 def remove(self, value): 682 """Remove an element. If not a member, raise a KeyError.""" 683 if value not in self: 684 raise KeyError(value) 685 self.discard(value) 686 687 def pop(self): 688 """Return the popped value. Raise KeyError if empty.""" 689 it = iter(self) 690 try: 691 value = next(it) 692 except StopIteration: 693 raise KeyError from None 694 self.discard(value) 695 return value 696 697 def clear(self): 698 """This is slow (creates N new iterators!) but effective.""" 699 try: 700 while True: 701 self.pop() 702 except KeyError: 703 pass 704 705 def __ior__(self, it): 706 for value in it: 707 self.add(value) 708 return self 709 710 def __iand__(self, it): 711 for value in (self - it): 712 self.discard(value) 713 return self 714 715 def __ixor__(self, it): 716 if it is self: 717 self.clear() 718 else: 719 if not isinstance(it, Set): 720 it = self._from_iterable(it) 721 for value in it: 722 if value in self: 723 self.discard(value) 724 else: 725 self.add(value) 726 return self 727 728 def __isub__(self, it): 729 if it is self: 730 self.clear() 731 else: 732 for value in it: 733 self.discard(value) 734 return self 735 736 737MutableSet.register(set) 738 739 740### MAPPINGS ### 741 742 743class Mapping(Collection): 744 745 __slots__ = () 746 747 """A Mapping is a generic container for associating key/value 748 pairs. 749 750 This class provides concrete generic implementations of all 751 methods except for __getitem__, __iter__, and __len__. 752 753 """ 754 755 @abstractmethod 756 def __getitem__(self, key): 757 raise KeyError 758 759 def get(self, key, default=None): 760 'D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.' 761 try: 762 return self[key] 763 except KeyError: 764 return default 765 766 def __contains__(self, key): 767 try: 768 self[key] 769 except KeyError: 770 return False 771 else: 772 return True 773 774 def keys(self): 775 "D.keys() -> a set-like object providing a view on D's keys" 776 return KeysView(self) 777 778 def items(self): 779 "D.items() -> a set-like object providing a view on D's items" 780 return ItemsView(self) 781 782 def values(self): 783 "D.values() -> an object providing a view on D's values" 784 return ValuesView(self) 785 786 def __eq__(self, other): 787 if not isinstance(other, Mapping): 788 return NotImplemented 789 return dict(self.items()) == dict(other.items()) 790 791 __reversed__ = None 792 793 794Mapping.register(mappingproxy) 795 796 797class MappingView(Sized): 798 799 __slots__ = '_mapping', 800 801 def __init__(self, mapping): 802 self._mapping = mapping 803 804 def __len__(self): 805 return len(self._mapping) 806 807 def __repr__(self): 808 return '{0.__class__.__name__}({0._mapping!r})'.format(self) 809 810 __class_getitem__ = classmethod(GenericAlias) 811 812 813class KeysView(MappingView, Set): 814 815 __slots__ = () 816 817 @classmethod 818 def _from_iterable(self, it): 819 return set(it) 820 821 def __contains__(self, key): 822 return key in self._mapping 823 824 def __iter__(self): 825 yield from self._mapping 826 827 828KeysView.register(dict_keys) 829 830 831class ItemsView(MappingView, Set): 832 833 __slots__ = () 834 835 @classmethod 836 def _from_iterable(self, it): 837 return set(it) 838 839 def __contains__(self, item): 840 key, value = item 841 try: 842 v = self._mapping[key] 843 except KeyError: 844 return False 845 else: 846 return v is value or v == value 847 848 def __iter__(self): 849 for key in self._mapping: 850 yield (key, self._mapping[key]) 851 852 853ItemsView.register(dict_items) 854 855 856class ValuesView(MappingView, Collection): 857 858 __slots__ = () 859 860 def __contains__(self, value): 861 for key in self._mapping: 862 v = self._mapping[key] 863 if v is value or v == value: 864 return True 865 return False 866 867 def __iter__(self): 868 for key in self._mapping: 869 yield self._mapping[key] 870 871 872ValuesView.register(dict_values) 873 874 875class MutableMapping(Mapping): 876 877 __slots__ = () 878 879 """A MutableMapping is a generic container for associating 880 key/value pairs. 881 882 This class provides concrete generic implementations of all 883 methods except for __getitem__, __setitem__, __delitem__, 884 __iter__, and __len__. 885 886 """ 887 888 @abstractmethod 889 def __setitem__(self, key, value): 890 raise KeyError 891 892 @abstractmethod 893 def __delitem__(self, key): 894 raise KeyError 895 896 __marker = object() 897 898 def pop(self, key, default=__marker): 899 '''D.pop(k[,d]) -> v, remove specified key and return the corresponding value. 900 If key is not found, d is returned if given, otherwise KeyError is raised. 901 ''' 902 try: 903 value = self[key] 904 except KeyError: 905 if default is self.__marker: 906 raise 907 return default 908 else: 909 del self[key] 910 return value 911 912 def popitem(self): 913 '''D.popitem() -> (k, v), remove and return some (key, value) pair 914 as a 2-tuple; but raise KeyError if D is empty. 915 ''' 916 try: 917 key = next(iter(self)) 918 except StopIteration: 919 raise KeyError from None 920 value = self[key] 921 del self[key] 922 return key, value 923 924 def clear(self): 925 'D.clear() -> None. Remove all items from D.' 926 try: 927 while True: 928 self.popitem() 929 except KeyError: 930 pass 931 932 def update(self, other=(), /, **kwds): 933 ''' D.update([E, ]**F) -> None. Update D from mapping/iterable E and F. 934 If E present and has a .keys() method, does: for k in E: D[k] = E[k] 935 If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v 936 In either case, this is followed by: for k, v in F.items(): D[k] = v 937 ''' 938 if isinstance(other, Mapping): 939 for key in other: 940 self[key] = other[key] 941 elif hasattr(other, "keys"): 942 for key in other.keys(): 943 self[key] = other[key] 944 else: 945 for key, value in other: 946 self[key] = value 947 for key, value in kwds.items(): 948 self[key] = value 949 950 def setdefault(self, key, default=None): 951 'D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D' 952 try: 953 return self[key] 954 except KeyError: 955 self[key] = default 956 return default 957 958 959MutableMapping.register(dict) 960 961 962### SEQUENCES ### 963 964 965class Sequence(Reversible, Collection): 966 967 """All the operations on a read-only sequence. 968 969 Concrete subclasses must override __new__ or __init__, 970 __getitem__, and __len__. 971 """ 972 973 __slots__ = () 974 975 @abstractmethod 976 def __getitem__(self, index): 977 raise IndexError 978 979 def __iter__(self): 980 i = 0 981 try: 982 while True: 983 v = self[i] 984 yield v 985 i += 1 986 except IndexError: 987 return 988 989 def __contains__(self, value): 990 for v in self: 991 if v is value or v == value: 992 return True 993 return False 994 995 def __reversed__(self): 996 for i in reversed(range(len(self))): 997 yield self[i] 998 999 def index(self, value, start=0, stop=None): 1000 '''S.index(value, [start, [stop]]) -> integer -- return first index of value. 1001 Raises ValueError if the value is not present. 1002 1003 Supporting start and stop arguments is optional, but 1004 recommended. 1005 ''' 1006 if start is not None and start < 0: 1007 start = max(len(self) + start, 0) 1008 if stop is not None and stop < 0: 1009 stop += len(self) 1010 1011 i = start 1012 while stop is None or i < stop: 1013 try: 1014 v = self[i] 1015 if v is value or v == value: 1016 return i 1017 except IndexError: 1018 break 1019 i += 1 1020 raise ValueError 1021 1022 def count(self, value): 1023 'S.count(value) -> integer -- return number of occurrences of value' 1024 return sum(1 for v in self if v is value or v == value) 1025 1026 1027Sequence.register(tuple) 1028Sequence.register(str) 1029Sequence.register(range) 1030Sequence.register(memoryview) 1031 1032 1033class ByteString(Sequence): 1034 1035 """This unifies bytes and bytearray. 1036 1037 XXX Should add all their methods. 1038 """ 1039 1040 __slots__ = () 1041 1042ByteString.register(bytes) 1043ByteString.register(bytearray) 1044 1045 1046class MutableSequence(Sequence): 1047 1048 __slots__ = () 1049 1050 """All the operations on a read-write sequence. 1051 1052 Concrete subclasses must provide __new__ or __init__, 1053 __getitem__, __setitem__, __delitem__, __len__, and insert(). 1054 1055 """ 1056 1057 @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): 1067 'S.insert(index, value) -- insert value before index' 1068 raise IndexError 1069 1070 def append(self, value): 1071 'S.append(value) -- append value to the end of the sequence' 1072 self.insert(len(self), value) 1073 1074 def clear(self): 1075 'S.clear() -> None -- remove all items from S' 1076 try: 1077 while True: 1078 self.pop() 1079 except IndexError: 1080 pass 1081 1082 def reverse(self): 1083 'S.reverse() -- reverse *IN PLACE*' 1084 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): 1089 'S.extend(iterable) -- extend sequence by appending elements from the iterable' 1090 if values is self: 1091 values = list(values) 1092 for v in values: 1093 self.append(v) 1094 1095 def pop(self, index=-1): 1096 '''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 ''' 1099 v = self[index] 1100 del self[index] 1101 return v 1102 1103 def remove(self, value): 1104 '''S.remove(value) -- remove first occurrence of value. 1105 Raise ValueError if the value is not present. 1106 ''' 1107 del self[self.index(value)] 1108 1109 def __iadd__(self, values): 1110 self.extend(values) 1111 return self 1112 1113 1114MutableSequence.register(list) 1115MutableSequence.register(bytearray) # Multiply inheriting, see ByteString 1116