ยปCore Development>Code coverage>Lib/_collections_abc.py

Python code coverage for Lib/_collections_abc.py

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