logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

_collections_abc.py (31949B)


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