_collections_abc.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  1. # Copyright 2007 Google, Inc. All Rights Reserved.
  2. # Licensed to PSF under a Contributor Agreement.
  3. """Abstract Base Classes (ABCs) for collections, according to PEP 3119.
  4. Unit tests are in test_collections.
  5. """
  6. ############ Maintenance notes #########################################
  7. #
  8. # ABCs are different from other standard library modules in that they
  9. # specify compliance tests. In general, once an ABC has been published,
  10. # new methods (either abstract or concrete) cannot be added.
  11. #
  12. # Though classes that inherit from an ABC would automatically receive a
  13. # new mixin method, registered classes would become non-compliant and
  14. # violate the contract promised by ``isinstance(someobj, SomeABC)``.
  15. #
  16. # Though irritating, the correct procedure for adding new abstract or
  17. # mixin methods is to create a new ABC as a subclass of the previous
  18. # ABC. For example, union(), intersection(), and difference() cannot
  19. # be added to Set but could go into a new ABC that extends Set.
  20. #
  21. # Because they are so hard to change, new ABCs should have their APIs
  22. # carefully thought through prior to publication.
  23. #
  24. # Since ABCMeta only checks for the presence of methods, it is possible
  25. # to alter the signature of a method by adding optional arguments
  26. # or changing parameters names. This is still a bit dubious but at
  27. # least it won't cause isinstance() to return an incorrect result.
  28. #
  29. #
  30. #######################################################################
  31. from abc import ABCMeta, abstractmethod
  32. import sys
  33. GenericAlias = type(list[int])
  34. EllipsisType = type(...)
  35. def _f(): pass
  36. FunctionType = type(_f)
  37. del _f
  38. __all__ = ["Awaitable", "Coroutine",
  39. "AsyncIterable", "AsyncIterator", "AsyncGenerator",
  40. "Hashable", "Iterable", "Iterator", "Generator", "Reversible",
  41. "Sized", "Container", "Callable", "Collection",
  42. "Set", "MutableSet",
  43. "Mapping", "MutableMapping",
  44. "MappingView", "KeysView", "ItemsView", "ValuesView",
  45. "Sequence", "MutableSequence",
  46. "ByteString", "Buffer",
  47. ]
  48. # This module has been renamed from collections.abc to _collections_abc to
  49. # speed up interpreter startup. Some of the types such as MutableMapping are
  50. # required early but collections module imports a lot of other modules.
  51. # See issue #19218
  52. __name__ = "collections.abc"
  53. # Private list of types that we want to register with the various ABCs
  54. # so that they will pass tests like:
  55. # it = iter(somebytearray)
  56. # assert isinstance(it, Iterable)
  57. # Note: in other implementations, these types might not be distinct
  58. # and they may have their own implementation specific types that
  59. # are not included on this list.
  60. bytes_iterator = type(iter(b''))
  61. bytearray_iterator = type(iter(bytearray()))
  62. #callable_iterator = ???
  63. dict_keyiterator = type(iter({}.keys()))
  64. dict_valueiterator = type(iter({}.values()))
  65. dict_itemiterator = type(iter({}.items()))
  66. list_iterator = type(iter([]))
  67. list_reverseiterator = type(iter(reversed([])))
  68. range_iterator = type(iter(range(0)))
  69. longrange_iterator = type(iter(range(1 << 1000)))
  70. set_iterator = type(iter(set()))
  71. str_iterator = type(iter(""))
  72. tuple_iterator = type(iter(()))
  73. zip_iterator = type(iter(zip()))
  74. ## views ##
  75. dict_keys = type({}.keys())
  76. dict_values = type({}.values())
  77. dict_items = type({}.items())
  78. ## misc ##
  79. mappingproxy = type(type.__dict__)
  80. generator = type((lambda: (yield))())
  81. ## coroutine ##
  82. async def _coro(): pass
  83. _coro = _coro()
  84. coroutine = type(_coro)
  85. _coro.close() # Prevent ResourceWarning
  86. del _coro
  87. ## asynchronous generator ##
  88. async def _ag(): yield
  89. _ag = _ag()
  90. async_generator = type(_ag)
  91. del _ag
  92. ### ONE-TRICK PONIES ###
  93. def _check_methods(C, *methods):
  94. mro = C.__mro__
  95. for method in methods:
  96. for B in mro:
  97. if method in B.__dict__:
  98. if B.__dict__[method] is None:
  99. return NotImplemented
  100. break
  101. else:
  102. return NotImplemented
  103. return True
  104. class Hashable(metaclass=ABCMeta):
  105. __slots__ = ()
  106. @abstractmethod
  107. def __hash__(self):
  108. return 0
  109. @classmethod
  110. def __subclasshook__(cls, C):
  111. if cls is Hashable:
  112. return _check_methods(C, "__hash__")
  113. return NotImplemented
  114. class Awaitable(metaclass=ABCMeta):
  115. __slots__ = ()
  116. @abstractmethod
  117. def __await__(self):
  118. yield
  119. @classmethod
  120. def __subclasshook__(cls, C):
  121. if cls is Awaitable:
  122. return _check_methods(C, "__await__")
  123. return NotImplemented
  124. __class_getitem__ = classmethod(GenericAlias)
  125. class Coroutine(Awaitable):
  126. __slots__ = ()
  127. @abstractmethod
  128. def send(self, value):
  129. """Send a value into the coroutine.
  130. Return next yielded value or raise StopIteration.
  131. """
  132. raise StopIteration
  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. def close(self):
  146. """Raise GeneratorExit inside coroutine.
  147. """
  148. try:
  149. self.throw(GeneratorExit)
  150. except (GeneratorExit, StopIteration):
  151. pass
  152. else:
  153. raise RuntimeError("coroutine ignored GeneratorExit")
  154. @classmethod
  155. def __subclasshook__(cls, C):
  156. if cls is Coroutine:
  157. return _check_methods(C, '__await__', 'send', 'throw', 'close')
  158. return NotImplemented
  159. Coroutine.register(coroutine)
  160. class AsyncIterable(metaclass=ABCMeta):
  161. __slots__ = ()
  162. @abstractmethod
  163. def __aiter__(self):
  164. return AsyncIterator()
  165. @classmethod
  166. def __subclasshook__(cls, C):
  167. if cls is AsyncIterable:
  168. return _check_methods(C, "__aiter__")
  169. return NotImplemented
  170. __class_getitem__ = classmethod(GenericAlias)
  171. class AsyncIterator(AsyncIterable):
  172. __slots__ = ()
  173. @abstractmethod
  174. async def __anext__(self):
  175. """Return the next item or raise StopAsyncIteration when exhausted."""
  176. raise StopAsyncIteration
  177. def __aiter__(self):
  178. return self
  179. @classmethod
  180. def __subclasshook__(cls, C):
  181. if cls is AsyncIterator:
  182. return _check_methods(C, "__anext__", "__aiter__")
  183. return NotImplemented
  184. class AsyncGenerator(AsyncIterator):
  185. __slots__ = ()
  186. async def __anext__(self):
  187. """Return the next item from the asynchronous generator.
  188. When exhausted, raise StopAsyncIteration.
  189. """
  190. return await self.asend(None)
  191. @abstractmethod
  192. async def asend(self, value):
  193. """Send a value into the asynchronous generator.
  194. Return next yielded value or raise StopAsyncIteration.
  195. """
  196. raise StopAsyncIteration
  197. @abstractmethod
  198. async def athrow(self, typ, val=None, tb=None):
  199. """Raise an exception in the asynchronous generator.
  200. Return next yielded value or raise StopAsyncIteration.
  201. """
  202. if val is None:
  203. if tb is None:
  204. raise typ
  205. val = typ()
  206. if tb is not None:
  207. val = val.with_traceback(tb)
  208. raise val
  209. async def aclose(self):
  210. """Raise GeneratorExit inside coroutine.
  211. """
  212. try:
  213. await self.athrow(GeneratorExit)
  214. except (GeneratorExit, StopAsyncIteration):
  215. pass
  216. else:
  217. raise RuntimeError("asynchronous generator ignored GeneratorExit")
  218. @classmethod
  219. def __subclasshook__(cls, C):
  220. if cls is AsyncGenerator:
  221. return _check_methods(C, '__aiter__', '__anext__',
  222. 'asend', 'athrow', 'aclose')
  223. return NotImplemented
  224. AsyncGenerator.register(async_generator)
  225. class Iterable(metaclass=ABCMeta):
  226. __slots__ = ()
  227. @abstractmethod
  228. def __iter__(self):
  229. while False:
  230. yield None
  231. @classmethod
  232. def __subclasshook__(cls, C):
  233. if cls is Iterable:
  234. return _check_methods(C, "__iter__")
  235. return NotImplemented
  236. __class_getitem__ = classmethod(GenericAlias)
  237. class Iterator(Iterable):
  238. __slots__ = ()
  239. @abstractmethod
  240. def __next__(self):
  241. 'Return the next item from the iterator. When exhausted, raise StopIteration'
  242. raise StopIteration
  243. def __iter__(self):
  244. return self
  245. @classmethod
  246. def __subclasshook__(cls, C):
  247. if cls is Iterator:
  248. return _check_methods(C, '__iter__', '__next__')
  249. return NotImplemented
  250. Iterator.register(bytes_iterator)
  251. Iterator.register(bytearray_iterator)
  252. #Iterator.register(callable_iterator)
  253. Iterator.register(dict_keyiterator)
  254. Iterator.register(dict_valueiterator)
  255. Iterator.register(dict_itemiterator)
  256. Iterator.register(list_iterator)
  257. Iterator.register(list_reverseiterator)
  258. Iterator.register(range_iterator)
  259. Iterator.register(longrange_iterator)
  260. Iterator.register(set_iterator)
  261. Iterator.register(str_iterator)
  262. Iterator.register(tuple_iterator)
  263. Iterator.register(zip_iterator)
  264. class Reversible(Iterable):
  265. __slots__ = ()
  266. @abstractmethod
  267. def __reversed__(self):
  268. while False:
  269. yield None
  270. @classmethod
  271. def __subclasshook__(cls, C):
  272. if cls is Reversible:
  273. return _check_methods(C, "__reversed__", "__iter__")
  274. return NotImplemented
  275. class Generator(Iterator):
  276. __slots__ = ()
  277. def __next__(self):
  278. """Return the next item from the generator.
  279. When exhausted, raise StopIteration.
  280. """
  281. return self.send(None)
  282. @abstractmethod
  283. def send(self, value):
  284. """Send a value into the generator.
  285. Return next yielded value or raise StopIteration.
  286. """
  287. raise StopIteration
  288. @abstractmethod
  289. def throw(self, typ, val=None, tb=None):
  290. """Raise an exception in the generator.
  291. Return next yielded value or raise StopIteration.
  292. """
  293. if val is None:
  294. if tb is None:
  295. raise typ
  296. val = typ()
  297. if tb is not None:
  298. val = val.with_traceback(tb)
  299. raise val
  300. def close(self):
  301. """Raise GeneratorExit inside generator.
  302. """
  303. try:
  304. self.throw(GeneratorExit)
  305. except (GeneratorExit, StopIteration):
  306. pass
  307. else:
  308. raise RuntimeError("generator ignored GeneratorExit")
  309. @classmethod
  310. def __subclasshook__(cls, C):
  311. if cls is Generator:
  312. return _check_methods(C, '__iter__', '__next__',
  313. 'send', 'throw', 'close')
  314. return NotImplemented
  315. Generator.register(generator)
  316. class Sized(metaclass=ABCMeta):
  317. __slots__ = ()
  318. @abstractmethod
  319. def __len__(self):
  320. return 0
  321. @classmethod
  322. def __subclasshook__(cls, C):
  323. if cls is Sized:
  324. return _check_methods(C, "__len__")
  325. return NotImplemented
  326. class Container(metaclass=ABCMeta):
  327. __slots__ = ()
  328. @abstractmethod
  329. def __contains__(self, x):
  330. return False
  331. @classmethod
  332. def __subclasshook__(cls, C):
  333. if cls is Container:
  334. return _check_methods(C, "__contains__")
  335. return NotImplemented
  336. __class_getitem__ = classmethod(GenericAlias)
  337. class Collection(Sized, Iterable, Container):
  338. __slots__ = ()
  339. @classmethod
  340. def __subclasshook__(cls, C):
  341. if cls is Collection:
  342. return _check_methods(C, "__len__", "__iter__", "__contains__")
  343. return NotImplemented
  344. class Buffer(metaclass=ABCMeta):
  345. __slots__ = ()
  346. @abstractmethod
  347. def __buffer__(self, flags: int, /) -> memoryview:
  348. raise NotImplementedError
  349. @classmethod
  350. def __subclasshook__(cls, C):
  351. if cls is Buffer:
  352. return _check_methods(C, "__buffer__")
  353. return NotImplemented
  354. class _CallableGenericAlias(GenericAlias):
  355. """ Represent `Callable[argtypes, resulttype]`.
  356. This sets ``__args__`` to a tuple containing the flattened ``argtypes``
  357. followed by ``resulttype``.
  358. Example: ``Callable[[int, str], float]`` sets ``__args__`` to
  359. ``(int, str, float)``.
  360. """
  361. __slots__ = ()
  362. def __new__(cls, origin, args):
  363. if not (isinstance(args, tuple) and len(args) == 2):
  364. raise TypeError(
  365. "Callable must be used as Callable[[arg, ...], result].")
  366. t_args, t_result = args
  367. if isinstance(t_args, (tuple, list)):
  368. args = (*t_args, t_result)
  369. elif not _is_param_expr(t_args):
  370. raise TypeError(f"Expected a list of types, an ellipsis, "
  371. f"ParamSpec, or Concatenate. Got {t_args}")
  372. return super().__new__(cls, origin, args)
  373. def __repr__(self):
  374. if len(self.__args__) == 2 and _is_param_expr(self.__args__[0]):
  375. return super().__repr__()
  376. return (f'collections.abc.Callable'
  377. f'[[{", ".join([_type_repr(a) for a in self.__args__[:-1]])}], '
  378. f'{_type_repr(self.__args__[-1])}]')
  379. def __reduce__(self):
  380. args = self.__args__
  381. if not (len(args) == 2 and _is_param_expr(args[0])):
  382. args = list(args[:-1]), args[-1]
  383. return _CallableGenericAlias, (Callable, args)
  384. def __getitem__(self, item):
  385. # Called during TypeVar substitution, returns the custom subclass
  386. # rather than the default types.GenericAlias object. Most of the
  387. # code is copied from typing's _GenericAlias and the builtin
  388. # types.GenericAlias.
  389. if not isinstance(item, tuple):
  390. item = (item,)
  391. new_args = super().__getitem__(item).__args__
  392. # args[0] occurs due to things like Z[[int, str, bool]] from PEP 612
  393. if not isinstance(new_args[0], (tuple, list)):
  394. t_result = new_args[-1]
  395. t_args = new_args[:-1]
  396. new_args = (t_args, t_result)
  397. return _CallableGenericAlias(Callable, tuple(new_args))
  398. def _is_param_expr(obj):
  399. """Checks if obj matches either a list of types, ``...``, ``ParamSpec`` or
  400. ``_ConcatenateGenericAlias`` from typing.py
  401. """
  402. if obj is Ellipsis:
  403. return True
  404. if isinstance(obj, list):
  405. return True
  406. obj = type(obj)
  407. names = ('ParamSpec', '_ConcatenateGenericAlias')
  408. return obj.__module__ == 'typing' and any(obj.__name__ == name for name in names)
  409. def _type_repr(obj):
  410. """Return the repr() of an object, special-casing types (internal helper).
  411. Copied from :mod:`typing` since collections.abc
  412. shouldn't depend on that module.
  413. (Keep this roughly in sync with the typing version.)
  414. """
  415. if isinstance(obj, type):
  416. if obj.__module__ == 'builtins':
  417. return obj.__qualname__
  418. return f'{obj.__module__}.{obj.__qualname__}'
  419. if obj is Ellipsis:
  420. return '...'
  421. if isinstance(obj, FunctionType):
  422. return obj.__name__
  423. return repr(obj)
  424. class Callable(metaclass=ABCMeta):
  425. __slots__ = ()
  426. @abstractmethod
  427. def __call__(self, *args, **kwds):
  428. return False
  429. @classmethod
  430. def __subclasshook__(cls, C):
  431. if cls is Callable:
  432. return _check_methods(C, "__call__")
  433. return NotImplemented
  434. __class_getitem__ = classmethod(_CallableGenericAlias)
  435. ### SETS ###
  436. class Set(Collection):
  437. """A set is a finite, iterable container.
  438. This class provides concrete generic implementations of all
  439. methods except for __contains__, __iter__ and __len__.
  440. To override the comparisons (presumably for speed, as the
  441. semantics are fixed), redefine __le__ and __ge__,
  442. then the other operations will automatically follow suit.
  443. """
  444. __slots__ = ()
  445. def __le__(self, other):
  446. if not isinstance(other, Set):
  447. return NotImplemented
  448. if len(self) > len(other):
  449. return False
  450. for elem in self:
  451. if elem not in other:
  452. return False
  453. return True
  454. def __lt__(self, other):
  455. if not isinstance(other, Set):
  456. return NotImplemented
  457. return len(self) < len(other) and self.__le__(other)
  458. def __gt__(self, other):
  459. if not isinstance(other, Set):
  460. return NotImplemented
  461. return len(self) > len(other) and self.__ge__(other)
  462. def __ge__(self, other):
  463. if not isinstance(other, Set):
  464. return NotImplemented
  465. if len(self) < len(other):
  466. return False
  467. for elem in other:
  468. if elem not in self:
  469. return False
  470. return True
  471. def __eq__(self, other):
  472. if not isinstance(other, Set):
  473. return NotImplemented
  474. return len(self) == len(other) and self.__le__(other)
  475. @classmethod
  476. def _from_iterable(cls, it):
  477. '''Construct an instance of the class from any iterable input.
  478. Must override this method if the class constructor signature
  479. does not accept an iterable for an input.
  480. '''
  481. return cls(it)
  482. def __and__(self, other):
  483. if not isinstance(other, Iterable):
  484. return NotImplemented
  485. return self._from_iterable(value for value in other if value in self)
  486. __rand__ = __and__
  487. def isdisjoint(self, other):
  488. 'Return True if two sets have a null intersection.'
  489. for value in other:
  490. if value in self:
  491. return False
  492. return True
  493. def __or__(self, other):
  494. if not isinstance(other, Iterable):
  495. return NotImplemented
  496. chain = (e for s in (self, other) for e in s)
  497. return self._from_iterable(chain)
  498. __ror__ = __or__
  499. def __sub__(self, other):
  500. if not isinstance(other, Set):
  501. if not isinstance(other, Iterable):
  502. return NotImplemented
  503. other = self._from_iterable(other)
  504. return self._from_iterable(value for value in self
  505. if value not in other)
  506. def __rsub__(self, other):
  507. if not isinstance(other, Set):
  508. if not isinstance(other, Iterable):
  509. return NotImplemented
  510. other = self._from_iterable(other)
  511. return self._from_iterable(value for value in other
  512. if value not in self)
  513. def __xor__(self, other):
  514. if not isinstance(other, Set):
  515. if not isinstance(other, Iterable):
  516. return NotImplemented
  517. other = self._from_iterable(other)
  518. return (self - other) | (other - self)
  519. __rxor__ = __xor__
  520. def _hash(self):
  521. """Compute the hash value of a set.
  522. Note that we don't define __hash__: not all sets are hashable.
  523. But if you define a hashable set type, its __hash__ should
  524. call this function.
  525. This must be compatible __eq__.
  526. All sets ought to compare equal if they contain the same
  527. elements, regardless of how they are implemented, and
  528. regardless of the order of the elements; so there's not much
  529. freedom for __eq__ or __hash__. We match the algorithm used
  530. by the built-in frozenset type.
  531. """
  532. MAX = sys.maxsize
  533. MASK = 2 * MAX + 1
  534. n = len(self)
  535. h = 1927868237 * (n + 1)
  536. h &= MASK
  537. for x in self:
  538. hx = hash(x)
  539. h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167
  540. h &= MASK
  541. h ^= (h >> 11) ^ (h >> 25)
  542. h = h * 69069 + 907133923
  543. h &= MASK
  544. if h > MAX:
  545. h -= MASK + 1
  546. if h == -1:
  547. h = 590923713
  548. return h
  549. Set.register(frozenset)
  550. class MutableSet(Set):
  551. """A mutable set is a finite, iterable container.
  552. This class provides concrete generic implementations of all
  553. methods except for __contains__, __iter__, __len__,
  554. add(), and discard().
  555. To override the comparisons (presumably for speed, as the
  556. semantics are fixed), all you have to do is redefine __le__ and
  557. then the other operations will automatically follow suit.
  558. """
  559. __slots__ = ()
  560. @abstractmethod
  561. def add(self, value):
  562. """Add an element."""
  563. raise NotImplementedError
  564. @abstractmethod
  565. def discard(self, value):
  566. """Remove an element. Do not raise an exception if absent."""
  567. raise NotImplementedError
  568. def remove(self, value):
  569. """Remove an element. If not a member, raise a KeyError."""
  570. if value not in self:
  571. raise KeyError(value)
  572. self.discard(value)
  573. def pop(self):
  574. """Return the popped value. Raise KeyError if empty."""
  575. it = iter(self)
  576. try:
  577. value = next(it)
  578. except StopIteration:
  579. raise KeyError from None
  580. self.discard(value)
  581. return value
  582. def clear(self):
  583. """This is slow (creates N new iterators!) but effective."""
  584. try:
  585. while True:
  586. self.pop()
  587. except KeyError:
  588. pass
  589. def __ior__(self, it):
  590. for value in it:
  591. self.add(value)
  592. return self
  593. def __iand__(self, it):
  594. for value in (self - it):
  595. self.discard(value)
  596. return self
  597. def __ixor__(self, it):
  598. if it is self:
  599. self.clear()
  600. else:
  601. if not isinstance(it, Set):
  602. it = self._from_iterable(it)
  603. for value in it:
  604. if value in self:
  605. self.discard(value)
  606. else:
  607. self.add(value)
  608. return self
  609. def __isub__(self, it):
  610. if it is self:
  611. self.clear()
  612. else:
  613. for value in it:
  614. self.discard(value)
  615. return self
  616. MutableSet.register(set)
  617. ### MAPPINGS ###
  618. class Mapping(Collection):
  619. """A Mapping is a generic container for associating key/value
  620. pairs.
  621. This class provides concrete generic implementations of all
  622. methods except for __getitem__, __iter__, and __len__.
  623. """
  624. __slots__ = ()
  625. # Tell ABCMeta.__new__ that this class should have TPFLAGS_MAPPING set.
  626. __abc_tpflags__ = 1 << 6 # Py_TPFLAGS_MAPPING
  627. @abstractmethod
  628. def __getitem__(self, key):
  629. raise KeyError
  630. def get(self, key, default=None):
  631. 'D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.'
  632. try:
  633. return self[key]
  634. except KeyError:
  635. return default
  636. def __contains__(self, key):
  637. try:
  638. self[key]
  639. except KeyError:
  640. return False
  641. else:
  642. return True
  643. def keys(self):
  644. "D.keys() -> a set-like object providing a view on D's keys"
  645. return KeysView(self)
  646. def items(self):
  647. "D.items() -> a set-like object providing a view on D's items"
  648. return ItemsView(self)
  649. def values(self):
  650. "D.values() -> an object providing a view on D's values"
  651. return ValuesView(self)
  652. def __eq__(self, other):
  653. if not isinstance(other, Mapping):
  654. return NotImplemented
  655. return dict(self.items()) == dict(other.items())
  656. __reversed__ = None
  657. Mapping.register(mappingproxy)
  658. class MappingView(Sized):
  659. __slots__ = '_mapping',
  660. def __init__(self, mapping):
  661. self._mapping = mapping
  662. def __len__(self):
  663. return len(self._mapping)
  664. def __repr__(self):
  665. return '{0.__class__.__name__}({0._mapping!r})'.format(self)
  666. __class_getitem__ = classmethod(GenericAlias)
  667. class KeysView(MappingView, Set):
  668. __slots__ = ()
  669. @classmethod
  670. def _from_iterable(cls, it):
  671. return set(it)
  672. def __contains__(self, key):
  673. return key in self._mapping
  674. def __iter__(self):
  675. yield from self._mapping
  676. KeysView.register(dict_keys)
  677. class ItemsView(MappingView, Set):
  678. __slots__ = ()
  679. @classmethod
  680. def _from_iterable(cls, it):
  681. return set(it)
  682. def __contains__(self, item):
  683. key, value = item
  684. try:
  685. v = self._mapping[key]
  686. except KeyError:
  687. return False
  688. else:
  689. return v is value or v == value
  690. def __iter__(self):
  691. for key in self._mapping:
  692. yield (key, self._mapping[key])
  693. ItemsView.register(dict_items)
  694. class ValuesView(MappingView, Collection):
  695. __slots__ = ()
  696. def __contains__(self, value):
  697. for key in self._mapping:
  698. v = self._mapping[key]
  699. if v is value or v == value:
  700. return True
  701. return False
  702. def __iter__(self):
  703. for key in self._mapping:
  704. yield self._mapping[key]
  705. ValuesView.register(dict_values)
  706. class MutableMapping(Mapping):
  707. """A MutableMapping is a generic container for associating
  708. key/value pairs.
  709. This class provides concrete generic implementations of all
  710. methods except for __getitem__, __setitem__, __delitem__,
  711. __iter__, and __len__.
  712. """
  713. __slots__ = ()
  714. @abstractmethod
  715. def __setitem__(self, key, value):
  716. raise KeyError
  717. @abstractmethod
  718. def __delitem__(self, key):
  719. raise KeyError
  720. __marker = object()
  721. def pop(self, key, default=__marker):
  722. '''D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
  723. If key is not found, d is returned if given, otherwise KeyError is raised.
  724. '''
  725. try:
  726. value = self[key]
  727. except KeyError:
  728. if default is self.__marker:
  729. raise
  730. return default
  731. else:
  732. del self[key]
  733. return value
  734. def popitem(self):
  735. '''D.popitem() -> (k, v), remove and return some (key, value) pair
  736. as a 2-tuple; but raise KeyError if D is empty.
  737. '''
  738. try:
  739. key = next(iter(self))
  740. except StopIteration:
  741. raise KeyError from None
  742. value = self[key]
  743. del self[key]
  744. return key, value
  745. def clear(self):
  746. 'D.clear() -> None. Remove all items from D.'
  747. try:
  748. while True:
  749. self.popitem()
  750. except KeyError:
  751. pass
  752. def update(self, other=(), /, **kwds):
  753. ''' D.update([E, ]**F) -> None. Update D from mapping/iterable E and F.
  754. If E present and has a .keys() method, does: for k in E: D[k] = E[k]
  755. If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
  756. In either case, this is followed by: for k, v in F.items(): D[k] = v
  757. '''
  758. if isinstance(other, Mapping):
  759. for key in other:
  760. self[key] = other[key]
  761. elif hasattr(other, "keys"):
  762. for key in other.keys():
  763. self[key] = other[key]
  764. else:
  765. for key, value in other:
  766. self[key] = value
  767. for key, value in kwds.items():
  768. self[key] = value
  769. def setdefault(self, key, default=None):
  770. 'D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D'
  771. try:
  772. return self[key]
  773. except KeyError:
  774. self[key] = default
  775. return default
  776. MutableMapping.register(dict)
  777. ### SEQUENCES ###
  778. class Sequence(Reversible, Collection):
  779. """All the operations on a read-only sequence.
  780. Concrete subclasses must override __new__ or __init__,
  781. __getitem__, and __len__.
  782. """
  783. __slots__ = ()
  784. # Tell ABCMeta.__new__ that this class should have TPFLAGS_SEQUENCE set.
  785. __abc_tpflags__ = 1 << 5 # Py_TPFLAGS_SEQUENCE
  786. @abstractmethod
  787. def __getitem__(self, index):
  788. raise IndexError
  789. def __iter__(self):
  790. i = 0
  791. try:
  792. while True:
  793. v = self[i]
  794. yield v
  795. i += 1
  796. except IndexError:
  797. return
  798. def __contains__(self, value):
  799. for v in self:
  800. if v is value or v == value:
  801. return True
  802. return False
  803. def __reversed__(self):
  804. for i in reversed(range(len(self))):
  805. yield self[i]
  806. def index(self, value, start=0, stop=None):
  807. '''S.index(value, [start, [stop]]) -> integer -- return first index of value.
  808. Raises ValueError if the value is not present.
  809. Supporting start and stop arguments is optional, but
  810. recommended.
  811. '''
  812. if start is not None and start < 0:
  813. start = max(len(self) + start, 0)
  814. if stop is not None and stop < 0:
  815. stop += len(self)
  816. i = start
  817. while stop is None or i < stop:
  818. try:
  819. v = self[i]
  820. except IndexError:
  821. break
  822. if v is value or v == value:
  823. return i
  824. i += 1
  825. raise ValueError
  826. def count(self, value):
  827. 'S.count(value) -> integer -- return number of occurrences of value'
  828. return sum(1 for v in self if v is value or v == value)
  829. Sequence.register(tuple)
  830. Sequence.register(str)
  831. Sequence.register(range)
  832. Sequence.register(memoryview)
  833. class _DeprecateByteStringMeta(ABCMeta):
  834. def __new__(cls, name, bases, namespace, **kwargs):
  835. if name != "ByteString":
  836. import warnings
  837. warnings._deprecated(
  838. "collections.abc.ByteString",
  839. remove=(3, 14),
  840. )
  841. return super().__new__(cls, name, bases, namespace, **kwargs)
  842. def __instancecheck__(cls, instance):
  843. import warnings
  844. warnings._deprecated(
  845. "collections.abc.ByteString",
  846. remove=(3, 14),
  847. )
  848. return super().__instancecheck__(instance)
  849. class ByteString(Sequence, metaclass=_DeprecateByteStringMeta):
  850. """This unifies bytes and bytearray.
  851. XXX Should add all their methods.
  852. """
  853. __slots__ = ()
  854. ByteString.register(bytes)
  855. ByteString.register(bytearray)
  856. class MutableSequence(Sequence):
  857. """All the operations on a read-write sequence.
  858. Concrete subclasses must provide __new__ or __init__,
  859. __getitem__, __setitem__, __delitem__, __len__, and insert().
  860. """
  861. __slots__ = ()
  862. @abstractmethod
  863. def __setitem__(self, index, value):
  864. raise IndexError
  865. @abstractmethod
  866. def __delitem__(self, index):
  867. raise IndexError
  868. @abstractmethod
  869. def insert(self, index, value):
  870. 'S.insert(index, value) -- insert value before index'
  871. raise IndexError
  872. def append(self, value):
  873. 'S.append(value) -- append value to the end of the sequence'
  874. self.insert(len(self), value)
  875. def clear(self):
  876. 'S.clear() -> None -- remove all items from S'
  877. try:
  878. while True:
  879. self.pop()
  880. except IndexError:
  881. pass
  882. def reverse(self):
  883. 'S.reverse() -- reverse *IN PLACE*'
  884. n = len(self)
  885. for i in range(n//2):
  886. self[i], self[n-i-1] = self[n-i-1], self[i]
  887. def extend(self, values):
  888. 'S.extend(iterable) -- extend sequence by appending elements from the iterable'
  889. if values is self:
  890. values = list(values)
  891. for v in values:
  892. self.append(v)
  893. def pop(self, index=-1):
  894. '''S.pop([index]) -> item -- remove and return item at index (default last).
  895. Raise IndexError if list is empty or index is out of range.
  896. '''
  897. v = self[index]
  898. del self[index]
  899. return v
  900. def remove(self, value):
  901. '''S.remove(value) -- remove first occurrence of value.
  902. Raise ValueError if the value is not present.
  903. '''
  904. del self[self.index(value)]
  905. def __iadd__(self, values):
  906. self.extend(values)
  907. return self
  908. MutableSequence.register(list)
  909. MutableSequence.register(bytearray) # Multiply inheriting, see ByteString