rip 2.7.x collections out
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kenneth Reitz · committed by Kenneth Reitz · parent ec926a4 · Browse files · 1 file·+991 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+991 added−0 removed
- other:+991 added−0 removed
Provenance
- Commit
0a4b735- Tree
c9545f0- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
ec926a4
1 file changed+991 added−0 removed
added:requests/packages/urllib3/__collections.py+991 added
1+from __future__ import with_statement2+3+4+# Copyright 2007 Google, Inc. All Rights Reserved.5+# Licensed to PSF under a Contributor Agreement.6+7+"""Abstract Base Classes (ABCs) according to PEP 3119."""8+9+import types10+11+from _weakref import ref12+13+__all__ = ['WeakSet']14+15+16+class _IterationGuard(object):17+ # This context manager registers itself in the current iterators of the18+ # weak container, such as to delay all removals until the context manager19+ # exits.20+ # This technique should be relatively thread-safe (since sets are).21+22+ def __init__(self, weakcontainer):23+ # Don't create cycles24+ self.weakcontainer = ref(weakcontainer)25+26+ def __enter__(self):27+ w = self.weakcontainer()28+ if w is not None:29+ w._iterating.add(self)30+ return self31+32+ def __exit__(self, e, t, b):33+ w = self.weakcontainer()34+ if w is not None:35+ s = w._iterating36+ s.remove(self)37+ if not s:38+ w._commit_removals()39+40+41+class WeakSet(object):42+ def __init__(self, data=None):43+ self.data = set()44+ def _remove(item, selfref=ref(self)):45+ self = selfref()46+ if self is not None:47+ if self._iterating:48+ self._pending_removals.append(item)49+ else:50+ self.data.discard(item)51+ self._remove = _remove52+ # A list of keys to be removed53+ self._pending_removals = []54+ self._iterating = set()55+ if data is not None:56+ self.update(data)57+58+ def _commit_removals(self):59+ l = self._pending_removals60+ discard = self.data.discard61+ while l:62+ discard(l.pop())63+64+ def __iter__(self):65+ with _IterationGuard(self):66+ for itemref in self.data:67+ item = itemref()68+ if item is not None:69+ yield item70+71+ def __len__(self):72+ return sum(x() is not None for x in self.data)73+74+ def __contains__(self, item):75+ try:76+ wr = ref(item)77+ except TypeError:78+ return False79+ return wr in self.data80+81+ def __reduce__(self):82+ return (self.__class__, (list(self),),83+ getattr(self, '__dict__', None))84+85+ __hash__ = None86+87+ def add(self, item):88+ if self._pending_removals:89+ self._commit_removals()90+ self.data.add(ref(item, self._remove))91+92+ def clear(self):93+ if self._pending_removals:94+ self._commit_removals()95+ self.data.clear()96+97+ def copy(self):98+ return self.__class__(self)99+100+ def pop(self):101+ if self._pending_removals:102+ self._commit_removals()103+ while True:104+ try:105+ itemref = self.data.pop()106+ except KeyError:107+ raise KeyError('pop from empty WeakSet')108+ item = itemref()109+ if item is not None:110+ return item111+112+ def remove(self, item):113+ if self._pending_removals:114+ self._commit_removals()115+ self.data.remove(ref(item))116+117+ def discard(self, item):118+ if self._pending_removals:119+ self._commit_removals()120+ self.data.discard(ref(item))121+122+ def update(self, other):123+ if self._pending_removals:124+ self._commit_removals()125+ if isinstance(other, self.__class__):126+ self.data.update(other.data)127+ else:128+ for element in other:129+ self.add(element)130+131+ def __ior__(self, other):132+ self.update(other)133+ return self134+135+ # Helper functions for simple delegating methods.136+ def _apply(self, other, method):137+ if not isinstance(other, self.__class__):138+ other = self.__class__(other)139+ newdata = method(other.data)140+ newset = self.__class__()141+ newset.data = newdata142+ return newset143+144+ def difference(self, other):145+ return self._apply(other, self.data.difference)146+ __sub__ = difference147+148+ def difference_update(self, other):149+ if self._pending_removals:150+ self._commit_removals()151+ if self is other:152+ self.data.clear()153+ else:154+ self.data.difference_update(ref(item) for item in other)155+ def __isub__(self, other):156+ if self._pending_removals:157+ self._commit_removals()158+ if self is other:159+ self.data.clear()160+ else:161+ self.data.difference_update(ref(item) for item in other)162+ return self163+164+ def intersection(self, other):165+ return self._apply(other, self.data.intersection)166+ __and__ = intersection167+168+ def intersection_update(self, other):169+ if self._pending_removals:170+ self._commit_removals()171+ self.data.intersection_update(ref(item) for item in other)172+ def __iand__(self, other):173+ if self._pending_removals:174+ self._commit_removals()175+ self.data.intersection_update(ref(item) for item in other)176+ return self177+178+ def issubset(self, other):179+ return self.data.issubset(ref(item) for item in other)180+ __lt__ = issubset181+182+ def __le__(self, other):183+ return self.data <= set(ref(item) for item in other)184+185+ def issuperset(self, other):186+ return self.data.issuperset(ref(item) for item in other)187+ __gt__ = issuperset188+189+ def __ge__(self, other):190+ return self.data >= set(ref(item) for item in other)191+192+ def __eq__(self, other):193+ if not isinstance(other, self.__class__):194+ return NotImplemented195+ return self.data == set(ref(item) for item in other)196+197+ def symmetric_difference(self, other):198+ return self._apply(other, self.data.symmetric_difference)199+ __xor__ = symmetric_difference200+201+ def symmetric_difference_update(self, other):202+ if self._pending_removals:203+ self._commit_removals()204+ if self is other:205+ self.data.clear()206+ else:207+ self.data.symmetric_difference_update(ref(item) for item in other)208+ def __ixor__(self, other):209+ if self._pending_removals:210+ self._commit_removals()211+ if self is other:212+ self.data.clear()213+ else:214+ self.data.symmetric_difference_update(ref(item) for item in other)215+ return self216+217+ def union(self, other):218+ return self._apply(other, self.data.union)219+ __or__ = union220+221+ def isdisjoint(self, other):222+ return len(self.intersection(other)) == 0223+224+225+# Instance of old-style class226+class _C: pass227+_InstanceType = type(_C())228+229+230+def abstractmethod(funcobj):231+ """A decorator indicating abstract methods.232+233+ Requires that the metaclass is ABCMeta or derived from it. A234+ class that has a metaclass derived from ABCMeta cannot be235+ instantiated unless all of its abstract methods are overridden.236+ The abstract methods can be called using any of the normal237+ 'super' call mechanisms.238+239+ Usage:240+241+ class C:242+ __metaclass__ = ABCMeta243+ @abstractmethod244+ def my_abstract_method(self, ...):245+ ...246+ """247+ funcobj.__isabstractmethod__ = True248+ return funcobj249+250+251+class abstractproperty(property):252+ """A decorator indicating abstract properties.253+254+ Requires that the metaclass is ABCMeta or derived from it. A255+ class that has a metaclass derived from ABCMeta cannot be256+ instantiated unless all of its abstract properties are overridden.257+ The abstract properties can be called using any of the normal258+ 'super' call mechanisms.259+260+ Usage:261+262+ class C:263+ __metaclass__ = ABCMeta264+ @abstractproperty265+ def my_abstract_property(self):266+ ...267+268+ This defines a read-only property; you can also define a read-write269+ abstract property using the 'long' form of property declaration:270+271+ class C:272+ __metaclass__ = ABCMeta273+ def getx(self): ...274+ def setx(self, value): ...275+ x = abstractproperty(getx, setx)276+ """277+ __isabstractmethod__ = True278+279+280+class ABCMeta(type):281+282+ """Metaclass for defining Abstract Base Classes (ABCs).283+284+ Use this metaclass to create an ABC. An ABC can be subclassed285+ directly, and then acts as a mix-in class. You can also register286+ unrelated concrete classes (even built-in classes) and unrelated287+ ABCs as 'virtual subclasses' -- these and their descendants will288+ be considered subclasses of the registering ABC by the built-in289+ issubclass() function, but the registering ABC won't show up in290+ their MRO (Method Resolution Order) nor will method291+ implementations defined by the registering ABC be callable (not292+ even via super()).293+294+ """295+296+ # A global counter that is incremented each time a class is297+ # registered as a virtual subclass of anything. It forces the298+ # negative cache to be cleared before its next use.299+ _abc_invalidation_counter = 0300+301+ def __new__(mcls, name, bases, namespace):302+ cls = super(ABCMeta, mcls).__new__(mcls, name, bases, namespace)303+ # Compute set of abstract method names304+ abstracts = set(name305+ for name, value in namespace.items()306+ if getattr(value, "__isabstractmethod__", False))307+ for base in bases:308+ for name in getattr(base, "__abstractmethods__", set()):309+ value = getattr(cls, name, None)310+ if getattr(value, "__isabstractmethod__", False):311+ abstracts.add(name)312+ cls.__abstractmethods__ = frozenset(abstracts)313+ # Set up inheritance registry314+ cls._abc_registry = WeakSet()315+ cls._abc_cache = WeakSet()316+ cls._abc_negative_cache = WeakSet()317+ cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter318+ return cls319+320+ def register(cls, subclass):321+ """Register a virtual subclass of an ABC."""322+ if not isinstance(subclass, (type, types.ClassType)):323+ raise TypeError("Can only register classes")324+ if issubclass(subclass, cls):325+ return # Already a subclass326+ # Subtle: test for cycles *after* testing for "already a subclass";327+ # this means we allow X.register(X) and interpret it as a no-op.328+ if issubclass(cls, subclass):329+ # This would create a cycle, which is bad for the algorithm below330+ raise RuntimeError("Refusing to create an inheritance cycle")331+ cls._abc_registry.add(subclass)332+ ABCMeta._abc_invalidation_counter += 1 # Invalidate negative cache333+334+ def _dump_registry(cls, file=None):335+ """Debug helper to print the ABC registry."""336+ print >> file, "Class: %s.%s" % (cls.__module__, cls.__name__)337+ print >> file, "Inv.counter: %s" % ABCMeta._abc_invalidation_counter338+ for name in sorted(cls.__dict__.keys()):339+ if name.startswith("_abc_"):340+ value = getattr(cls, name)341+ print >> file, "%s: %r" % (name, value)342+343+ def __instancecheck__(cls, instance):344+ """Override for isinstance(instance, cls)."""345+ # Inline the cache checking when it's simple.346+ subclass = getattr(instance, '__class__', None)347+ if subclass is not None and subclass in cls._abc_cache:348+ return True349+ subtype = type(instance)350+ # Old-style instances351+ if subtype is _InstanceType:352+ subtype = subclass353+ if subtype is subclass or subclass is None:354+ if (cls._abc_negative_cache_version ==355+ ABCMeta._abc_invalidation_counter and356+ subtype in cls._abc_negative_cache):357+ return False358+ # Fall back to the subclass check.359+ return cls.__subclasscheck__(subtype)360+ return (cls.__subclasscheck__(subclass) or361+ cls.__subclasscheck__(subtype))362+363+ def __subclasscheck__(cls, subclass):364+ """Override for issubclass(subclass, cls)."""365+ # Check cache366+ if subclass in cls._abc_cache:367+ return True368+ # Check negative cache; may have to invalidate369+ if cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter:370+ # Invalidate the negative cache371+ cls._abc_negative_cache = WeakSet()372+ cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter373+ elif subclass in cls._abc_negative_cache:374+ return False375+ # Check the subclass hook376+ ok = cls.__subclasshook__(subclass)377+ if ok is not NotImplemented:378+ assert isinstance(ok, bool)379+ if ok:380+ cls._abc_cache.add(subclass)381+ else:382+ cls._abc_negative_cache.add(subclass)383+ return ok384+ # Check if it's a direct subclass385+ if cls in getattr(subclass, '__mro__', ()):386+ cls._abc_cache.add(subclass)387+ return True388+ # Check if it's a subclass of a registered class (recursive)389+ for rcls in cls._abc_registry:390+ if issubclass(subclass, rcls):391+ cls._abc_cache.add(subclass)392+ return True393+ # Check if it's a subclass of a subclass (recursive)394+ for scls in cls.__subclasses__():395+ if issubclass(subclass, scls):396+ cls._abc_cache.add(subclass)397+ return True398+ # No dice; update negative cache399+ cls._abc_negative_cache.add(subclass)400+ return False401+402+403+404+405+406+407+408+409+import sys410+411+### ONE-TRICK PONIES ###412+413+def _hasattr(C, attr):414+ try:415+ return any(attr in B.__dict__ for B in C.__mro__)416+ except AttributeError:417+ # Old-style class418+ return hasattr(C, attr)419+420+421+class Hashable:422+ __metaclass__ = ABCMeta423+424+ @abstractmethod425+ def __hash__(self):426+ return 0427+428+ @classmethod429+ def __subclasshook__(cls, C):430+ if cls is Hashable:431+ try:432+ for B in C.__mro__:433+ if "__hash__" in B.__dict__:434+ if B.__dict__["__hash__"]:435+ return True436+ break437+ except AttributeError:438+ # Old-style class439+ if getattr(C, "__hash__", None):440+ return True441+ return NotImplemented442+443+444+class Iterable:445+ __metaclass__ = ABCMeta446+447+ @abstractmethod448+ def __iter__(self):449+ while False:450+ yield None451+452+ @classmethod453+ def __subclasshook__(cls, C):454+ if cls is Iterable:455+ if _hasattr(C, "__iter__"):456+ return True457+ return NotImplemented458+459+Iterable.register(str)460+461+462+class Iterator(Iterable):463+464+ @abstractmethod465+ def next(self):466+ raise StopIteration467+468+ def __iter__(self):469+ return self470+471+ @classmethod472+ def __subclasshook__(cls, C):473+ if cls is Iterator:474+ if _hasattr(C, "next") and _hasattr(C, "__iter__"):475+ return True476+ return NotImplemented477+478+479+class Sized:480+ __metaclass__ = ABCMeta481+482+ @abstractmethod483+ def __len__(self):484+ return 0485+486+ @classmethod487+ def __subclasshook__(cls, C):488+ if cls is Sized:489+ if _hasattr(C, "__len__"):490+ return True491+ return NotImplemented492+493+494+class Container:495+ __metaclass__ = ABCMeta496+497+ @abstractmethod498+ def __contains__(self, x):499+ return False500+501+ @classmethod502+ def __subclasshook__(cls, C):503+ if cls is Container:504+ if _hasattr(C, "__contains__"):505+ return True506+ return NotImplemented507+508+509+class Callable:510+ __metaclass__ = ABCMeta511+512+ @abstractmethod513+ def __call__(self, *args, **kwds):514+ return False515+516+ @classmethod517+ def __subclasshook__(cls, C):518+ if cls is Callable:519+ if _hasattr(C, "__call__"):520+ return True521+ return NotImplemented522+523+524+### SETS ###525+526+527+class Set(Sized, Iterable, Container):528+ """A set is a finite, iterable container.529+530+ This class provides concrete generic implementations of all531+ methods except for __contains__, __iter__ and __len__.532+533+ To override the comparisons (presumably for speed, as the534+ semantics are fixed), all you have to do is redefine __le__ and535+ then the other operations will automatically follow suit.536+ """537+538+ def __le__(self, other):539+ if not isinstance(other, Set):540+ return NotImplemented541+ if len(self) > len(other):542+ return False543+ for elem in self:544+ if elem not in other:545+ return False546+ return True547+548+ def __lt__(self, other):549+ if not isinstance(other, Set):550+ return NotImplemented551+ return len(self) < len(other) and self.__le__(other)552+553+ def __gt__(self, other):554+ if not isinstance(other, Set):555+ return NotImplemented556+ return other < self557+558+ def __ge__(self, other):559+ if not isinstance(other, Set):560+ return NotImplemented561+ return other <= self562+563+ def __eq__(self, other):564+ if not isinstance(other, Set):565+ return NotImplemented566+ return len(self) == len(other) and self.__le__(other)567+568+ def __ne__(self, other):569+ return not (self == other)570+571+ @classmethod572+ def _from_iterable(cls, it):573+ '''Construct an instance of the class from any iterable input.574+575+ Must override this method if the class constructor signature576+ does not accept an iterable for an input.577+ '''578+ return cls(it)579+580+ def __and__(self, other):581+ if not isinstance(other, Iterable):582+ return NotImplemented583+ return self._from_iterable(value for value in other if value in self)584+585+ def isdisjoint(self, other):586+ for value in other:587+ if value in self:588+ return False589+ return True590+591+ def __or__(self, other):592+ if not isinstance(other, Iterable):593+ return NotImplemented594+ chain = (e for s in (self, other) for e in s)595+ return self._from_iterable(chain)596+597+ def __sub__(self, other):598+ if not isinstance(other, Set):599+ if not isinstance(other, Iterable):600+ return NotImplemented601+ other = self._from_iterable(other)602+ return self._from_iterable(value for value in self603+ if value not in other)604+605+ def __xor__(self, other):606+ if not isinstance(other, Set):607+ if not isinstance(other, Iterable):608+ return NotImplemented609+ other = self._from_iterable(other)610+ return (self - other) | (other - self)611+612+ # Sets are not hashable by default, but subclasses can change this613+ __hash__ = None614+615+ def _hash(self):616+ """Compute the hash value of a set.617+618+ Note that we don't define __hash__: not all sets are hashable.619+ But if you define a hashable set type, its __hash__ should620+ call this function.621+622+ This must be compatible __eq__.623+624+ All sets ought to compare equal if they contain the same625+ elements, regardless of how they are implemented, and626+ regardless of the order of the elements; so there's not much627+ freedom for __eq__ or __hash__. We match the algorithm used628+ by the built-in frozenset type.629+ """630+ MAX = sys.maxint631+ MASK = 2 * MAX + 1632+ n = len(self)633+ h = 1927868237 * (n + 1)634+ h &= MASK635+ for x in self:636+ hx = hash(x)637+ h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167638+ h &= MASK639+ h = h * 69069 + 907133923640+ h &= MASK641+ if h > MAX:642+ h -= MASK + 1643+ if h == -1:644+ h = 590923713645+ return h646+647+Set.register(frozenset)648+649+650+class MutableSet(Set):651+652+ @abstractmethod653+ def add(self, value):654+ """Add an element."""655+ raise NotImplementedError656+657+ @abstractmethod658+ def discard(self, value):659+ """Remove an element. Do not raise an exception if absent."""660+ raise NotImplementedError661+662+ def remove(self, value):663+ """Remove an element. If not a member, raise a KeyError."""664+ if value not in self:665+ raise KeyError(value)666+ self.discard(value)667+668+ def pop(self):669+ """Return the popped value. Raise KeyError if empty."""670+ it = iter(self)671+ try:672+ value = next(it)673+ except StopIteration:674+ raise KeyError675+ self.discard(value)676+ return value677+678+ def clear(self):679+ """This is slow (creates N new iterators!) but effective."""680+ try:681+ while True:682+ self.pop()683+ except KeyError:684+ pass685+686+ def __ior__(self, it):687+ for value in it:688+ self.add(value)689+ return self690+691+ def __iand__(self, it):692+ for value in (self - it):693+ self.discard(value)694+ return self695+696+ def __ixor__(self, it):697+ if it is self:698+ self.clear()699+ else:700+ if not isinstance(it, Set):701+ it = self._from_iterable(it)702+ for value in it:703+ if value in self:704+ self.discard(value)705+ else:706+ self.add(value)707+ return self708+709+ def __isub__(self, it):710+ if it is self:711+ self.clear()712+ else:713+ for value in it:714+ self.discard(value)715+ return self716+717+MutableSet.register(set)718+719+720+### MAPPINGS ###721+722+723+class Mapping(Sized, Iterable, Container):724+725+ @abstractmethod726+ def __getitem__(self, key):727+ raise KeyError728+729+ def get(self, key, default=None):730+ try:731+ return self[key]732+ except KeyError:733+ return default734+735+ def __contains__(self, key):736+ try:737+ self[key]738+ except KeyError:739+ return False740+ else:741+ return True742+743+ def iterkeys(self):744+ return iter(self)745+746+ def itervalues(self):747+ for key in self:748+ yield self[key]749+750+ def iteritems(self):751+ for key in self:752+ yield (key, self[key])753+754+ def keys(self):755+ return list(self)756+757+ def items(self):758+ return [(key, self[key]) for key in self]759+760+ def values(self):761+ return [self[key] for key in self]762+763+ # Mappings are not hashable by default, but subclasses can change this764+ __hash__ = None765+766+ def __eq__(self, other):767+ if not isinstance(other, Mapping):768+ return NotImplemented769+ return dict(self.items()) == dict(other.items())770+771+ def __ne__(self, other):772+ return not (self == other)773+774+class MappingView(Sized):775+776+ def __init__(self, mapping):777+ self._mapping = mapping778+779+ def __len__(self):780+ return len(self._mapping)781+782+ def __repr__(self):783+ return '{0.__class__.__name__}({0._mapping!r})'.format(self)784+785+786+class KeysView(MappingView, Set):787+788+ @classmethod789+ def _from_iterable(self, it):790+ return set(it)791+792+ def __contains__(self, key):793+ return key in self._mapping794+795+ def __iter__(self):796+ for key in self._mapping:797+ yield key798+799+800+class ItemsView(MappingView, Set):801+802+ @classmethod803+ def _from_iterable(self, it):804+ return set(it)805+806+ def __contains__(self, item):807+ key, value = item808+ try:809+ v = self._mapping[key]810+ except KeyError:811+ return False812+ else:813+ return v == value814+815+ def __iter__(self):816+ for key in self._mapping:817+ yield (key, self._mapping[key])818+819+820+class ValuesView(MappingView):821+822+ def __contains__(self, value):823+ for key in self._mapping:824+ if value == self._mapping[key]:825+ return True826+ return False827+828+ def __iter__(self):829+ for key in self._mapping:830+ yield self._mapping[key]831+832+833+class MutableMapping(Mapping):834+835+ @abstractmethod836+ def __setitem__(self, key, value):837+ raise KeyError838+839+ @abstractmethod840+ def __delitem__(self, key):841+ raise KeyError842+843+ __marker = object()844+845+ def pop(self, key, default=__marker):846+ try:847+ value = self[key]848+ except KeyError:849+ if default is self.__marker:850+ raise851+ return default852+ else:853+ del self[key]854+ return value855+856+ def popitem(self):857+ try:858+ key = next(iter(self))859+ except StopIteration:860+ raise KeyError861+ value = self[key]862+ del self[key]863+ return key, value864+865+ def clear(self):866+ try:867+ while True:868+ self.popitem()869+ except KeyError:870+ pass871+872+ def update(*args, **kwds):873+ if len(args) > 2:874+ raise TypeError("update() takes at most 2 positional "875+ "arguments ({} given)".format(len(args)))876+ elif not args:877+ raise TypeError("update() takes at least 1 argument (0 given)")878+ self = args[0]879+ other = args[1] if len(args) >= 2 else ()880+881+ if isinstance(other, Mapping):882+ for key in other:883+ self[key] = other[key]884+ elif hasattr(other, "keys"):885+ for key in other.keys():886+ self[key] = other[key]887+ else:888+ for key, value in other:889+ self[key] = value890+ for key, value in kwds.items():891+ self[key] = value892+893+ def setdefault(self, key, default=None):894+ try:895+ return self[key]896+ except KeyError:897+ self[key] = default898+ return default899+900+MutableMapping.register(dict)901+902+903+### SEQUENCES ###904+905+906+class Sequence(Sized, Iterable, Container):907+ """All the operations on a read-only sequence.908+909+ Concrete subclasses must override __new__ or __init__,910+ __getitem__, and __len__.911+ """912+913+ @abstractmethod914+ def __getitem__(self, index):915+ raise IndexError916+917+ def __iter__(self):918+ i = 0919+ try:920+ while True:921+ v = self[i]922+ yield v923+ i += 1924+ except IndexError:925+ return926+927+ def __contains__(self, value):928+ for v in self:929+ if v == value:930+ return True931+ return False932+933+ def __reversed__(self):934+ for i in reversed(range(len(self))):935+ yield self[i]936+937+ def index(self, value):938+ for i, v in enumerate(self):939+ if v == value:940+ return i941+ raise ValueError942+943+ def count(self, value):944+ return sum(1 for v in self if v == value)945+946+Sequence.register(tuple)947+Sequence.register(basestring)948+Sequence.register(buffer)949+Sequence.register(xrange)950+951+952+class MutableSequence(Sequence):953+954+ @abstractmethod955+ def __setitem__(self, index, value):956+ raise IndexError957+958+ @abstractmethod959+ def __delitem__(self, index):960+ raise IndexError961+962+ @abstractmethod963+ def insert(self, index, value):964+ raise IndexError965+966+ def append(self, value):967+ self.insert(len(self), value)968+969+ def reverse(self):970+ n = len(self)971+ for i in range(n//2):972+ self[i], self[n-i-1] = self[n-i-1], self[i]973+974+ def extend(self, values):975+ for v in values:976+ self.append(v)977+978+ def pop(self, index=-1):979+ v = self[index]980+ del self[index]981+ return v982+983+ def remove(self, value):984+ del self[self.index(value)]985+986+ def __iadd__(self, values):987+ self.extend(values)988+ return self989+990+MutableSequence.register(list)991+