_compat.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  1. # _compat.py -- For dealing with python2.6 oddness
  2. # Copyright (C) 2012-2014 Jelmer Vernooij and others.
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; version 2
  7. # of the License or (at your option) a later version of the License.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  17. # MA 02110-1301, USA.
  18. """Misc utilities to work with python <2.7.
  19. These utilities can all be deleted when dulwich decides it wants to stop
  20. support for python <2.7.
  21. """
  22. # Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and
  23. # pypy. Passes Python2.7's test suite and incorporates all the latest updates.
  24. # Copyright (C) Raymond Hettinger, MIT license
  25. try:
  26. from thread import get_ident as _get_ident
  27. except ImportError:
  28. from dummy_thread import get_ident as _get_ident
  29. try:
  30. from _abcoll import KeysView, ValuesView, ItemsView
  31. except ImportError:
  32. pass
  33. class OrderedDict(dict):
  34. 'Dictionary that remembers insertion order'
  35. # An inherited dict maps keys to values.
  36. # The inherited dict provides __getitem__, __len__, __contains__, and get.
  37. # The remaining methods are order-aware.
  38. # Big-O running times for all methods are the same as for regular
  39. # dictionaries.
  40. # The internal self.__map dictionary maps keys to links in a doubly linked
  41. # list. The circular doubly linked list starts and ends with a sentinel
  42. # element. The sentinel element never gets deleted (this simplifies the
  43. # algorithm). Each link is stored as a list of length three: [PREV, NEXT,
  44. # KEY].
  45. def __init__(self, *args, **kwds):
  46. '''Initialize an ordered dictionary. Signature is the same as for
  47. regular dictionaries, but keyword arguments are not recommended
  48. because their insertion order is arbitrary.
  49. '''
  50. if len(args) > 1:
  51. raise TypeError('expected at most 1 arguments, got %d' % len(args))
  52. try:
  53. self.__root
  54. except AttributeError:
  55. self.__root = root = [] # sentinel node
  56. root[:] = [root, root, None]
  57. self.__map = {}
  58. self.__update(*args, **kwds)
  59. def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
  60. 'od.__setitem__(i, y) <==> od[i]=y'
  61. # Setting a new item creates a new link which goes at the end of the
  62. # linked list, and the inherited dictionary is updated with the new
  63. # key/value pair.
  64. if key not in self:
  65. root = self.__root
  66. last = root[0]
  67. last[1] = root[0] = self.__map[key] = [last, root, key]
  68. dict_setitem(self, key, value)
  69. def __delitem__(self, key, dict_delitem=dict.__delitem__):
  70. 'od.__delitem__(y) <==> del od[y]'
  71. # Deleting an existing item uses self.__map to find the link which is
  72. # then removed by updating the links in the predecessor and successor
  73. # nodes.
  74. dict_delitem(self, key)
  75. link_prev, link_next, key = self.__map.pop(key)
  76. link_prev[1] = link_next
  77. link_next[0] = link_prev
  78. def __iter__(self):
  79. 'od.__iter__() <==> iter(od)'
  80. root = self.__root
  81. curr = root[1]
  82. while curr is not root:
  83. yield curr[2]
  84. curr = curr[1]
  85. def __reversed__(self):
  86. 'od.__reversed__() <==> reversed(od)'
  87. root = self.__root
  88. curr = root[0]
  89. while curr is not root:
  90. yield curr[2]
  91. curr = curr[0]
  92. def clear(self):
  93. 'od.clear() -> None. Remove all items from od.'
  94. try:
  95. for node in self.__map.itervalues():
  96. del node[:]
  97. root = self.__root
  98. root[:] = [root, root, None]
  99. self.__map.clear()
  100. except AttributeError:
  101. pass
  102. dict.clear(self)
  103. def popitem(self, last=True):
  104. """od.popitem() -> (k, v), return and remove a (key, value) pair.
  105. Pairs are returned in LIFO order if last is true or FIFO order if false.
  106. """
  107. if not self:
  108. raise KeyError('dictionary is empty')
  109. root = self.__root
  110. if last:
  111. link = root[0]
  112. link_prev = link[0]
  113. link_prev[1] = root
  114. root[0] = link_prev
  115. else:
  116. link = root[1]
  117. link_next = link[1]
  118. root[1] = link_next
  119. link_next[0] = root
  120. key = link[2]
  121. del self.__map[key]
  122. value = dict.pop(self, key)
  123. return key, value
  124. # -- the following methods do not depend on the internal structure --
  125. def keys(self):
  126. """'od.keys() -> list of keys in od"""
  127. return list(self)
  128. def values(self):
  129. """od.values() -> list of values in od"""
  130. return [self[key] for key in self]
  131. def items(self):
  132. """od.items() -> list of (key, value) pairs in od"""
  133. return [(key, self[key]) for key in self]
  134. def iterkeys(self):
  135. """od.iterkeys() -> an iterator over the keys in od"""
  136. return iter(self)
  137. def itervalues(self):
  138. """od.itervalues -> an iterator over the values in od"""
  139. for k in self:
  140. yield self[k]
  141. def iteritems(self):
  142. """od.iteritems -> an iterator over the (key, value) items in od"""
  143. for k in self:
  144. yield (k, self[k])
  145. def update(*args, **kwds):
  146. """od.update(E, F) -> None. Update od from dict/iterable E and F.
  147. If E is a dict instance, does: for k in E: od[k] = E[k]
  148. If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]
  149. Or if E is an iterable of items, does: for k, v in E: od[k] = v
  150. In either case, this is followed by: for k, v in F.items(): od[k] = v
  151. """
  152. if len(args) > 2:
  153. raise TypeError('update() takes at most 2 positional '
  154. 'arguments (%d given)' % (len(args),))
  155. elif not args:
  156. raise TypeError('update() takes at least 1 argument (0 given)')
  157. self = args[0]
  158. # Make progressively weaker assumptions about "other"
  159. other = ()
  160. if len(args) == 2:
  161. other = args[1]
  162. if isinstance(other, dict):
  163. for key in other:
  164. self[key] = other[key]
  165. elif hasattr(other, 'keys'):
  166. for key in other.keys():
  167. self[key] = other[key]
  168. else:
  169. for key, value in other:
  170. self[key] = value
  171. for key, value in kwds.items():
  172. self[key] = value
  173. __update = update # let subclasses override update without breaking
  174. # __init__
  175. __marker = object()
  176. def pop(self, key, default=__marker):
  177. """od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
  178. If key is not found, d is returned if given, otherwise KeyError is raised.
  179. """
  180. if key in self:
  181. result = self[key]
  182. del self[key]
  183. return result
  184. if default is self.__marker:
  185. raise KeyError(key)
  186. return default
  187. def setdefault(self, key, default=None):
  188. 'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
  189. if key in self:
  190. return self[key]
  191. self[key] = default
  192. return default
  193. def __repr__(self, _repr_running={}):
  194. 'od.__repr__() <==> repr(od)'
  195. call_key = id(self), _get_ident()
  196. if call_key in _repr_running:
  197. return '...'
  198. _repr_running[call_key] = 1
  199. try:
  200. if not self:
  201. return '%s()' % (self.__class__.__name__,)
  202. return '%s(%r)' % (self.__class__.__name__, self.items())
  203. finally:
  204. del _repr_running[call_key]
  205. def __reduce__(self):
  206. 'Return state information for pickling'
  207. items = [[k, self[k]] for k in self]
  208. inst_dict = vars(self).copy()
  209. for k in vars(OrderedDict()):
  210. inst_dict.pop(k, None)
  211. if inst_dict:
  212. return (self.__class__, (items,), inst_dict)
  213. return self.__class__, (items,)
  214. def copy(self):
  215. 'od.copy() -> a shallow copy of od'
  216. return self.__class__(self)
  217. @classmethod
  218. def fromkeys(cls, iterable, value=None):
  219. '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
  220. and values equal to v (which defaults to None).
  221. '''
  222. d = cls()
  223. for key in iterable:
  224. d[key] = value
  225. return d
  226. def __eq__(self, other):
  227. '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
  228. while comparison to a regular mapping is order-insensitive.
  229. '''
  230. if isinstance(other, OrderedDict):
  231. return len(self)==len(other) and self.items() == other.items()
  232. return dict.__eq__(self, other)
  233. def __ne__(self, other):
  234. return not self == other
  235. # -- the following methods are only used in Python 2.7 --
  236. def viewkeys(self):
  237. "od.viewkeys() -> a set-like object providing a view on od's keys"
  238. return KeysView(self)
  239. def viewvalues(self):
  240. "od.viewvalues() -> an object providing a view on od's values"
  241. return ValuesView(self)
  242. def viewitems(self):
  243. "od.viewitems() -> a set-like object providing a view on od's items"
  244. return ItemsView(self)
  245. # Copyright 2007 Google, Inc. All Rights Reserved.
  246. # Licensed to PSF under a Contributor Agreement.
  247. from abc import ABCMeta, abstractmethod
  248. import sys
  249. ### ONE-TRICK PONIES ###
  250. def _hasattr(C, attr):
  251. try:
  252. return any(attr in B.__dict__ for B in C.__mro__)
  253. except AttributeError:
  254. # Old-style class
  255. return hasattr(C, attr)
  256. class Hashable:
  257. __metaclass__ = ABCMeta
  258. @abstractmethod
  259. def __hash__(self):
  260. return 0
  261. @classmethod
  262. def __subclasshook__(cls, C):
  263. if cls is Hashable:
  264. try:
  265. for B in C.__mro__:
  266. if "__hash__" in B.__dict__:
  267. if B.__dict__["__hash__"]:
  268. return True
  269. break
  270. except AttributeError:
  271. # Old-style class
  272. if getattr(C, "__hash__", None):
  273. return True
  274. return NotImplemented
  275. class Iterable:
  276. __metaclass__ = ABCMeta
  277. @abstractmethod
  278. def __iter__(self):
  279. while False:
  280. yield None
  281. @classmethod
  282. def __subclasshook__(cls, C):
  283. if cls is Iterable:
  284. if _hasattr(C, "__iter__"):
  285. return True
  286. return NotImplemented
  287. Iterable.register(str)
  288. class Iterator(Iterable):
  289. @abstractmethod
  290. def next(self):
  291. 'Return the next item from the iterator. When exhausted, raise StopIteration'
  292. raise StopIteration
  293. def __iter__(self):
  294. return self
  295. @classmethod
  296. def __subclasshook__(cls, C):
  297. if cls is Iterator:
  298. if _hasattr(C, "next") and _hasattr(C, "__iter__"):
  299. return True
  300. return NotImplemented
  301. class Sized:
  302. __metaclass__ = ABCMeta
  303. @abstractmethod
  304. def __len__(self):
  305. return 0
  306. @classmethod
  307. def __subclasshook__(cls, C):
  308. if cls is Sized:
  309. if _hasattr(C, "__len__"):
  310. return True
  311. return NotImplemented
  312. class Container:
  313. __metaclass__ = ABCMeta
  314. @abstractmethod
  315. def __contains__(self, x):
  316. return False
  317. @classmethod
  318. def __subclasshook__(cls, C):
  319. if cls is Container:
  320. if _hasattr(C, "__contains__"):
  321. return True
  322. return NotImplemented
  323. class Callable:
  324. __metaclass__ = ABCMeta
  325. @abstractmethod
  326. def __call__(self, *args, **kwds):
  327. return False
  328. @classmethod
  329. def __subclasshook__(cls, C):
  330. if cls is Callable:
  331. if _hasattr(C, "__call__"):
  332. return True
  333. return NotImplemented
  334. ### SETS ###
  335. class Set(Sized, Iterable, Container):
  336. """A set is a finite, iterable container.
  337. This class provides concrete generic implementations of all
  338. methods except for __contains__, __iter__ and __len__.
  339. To override the comparisons (presumably for speed, as the
  340. semantics are fixed), all you have to do is redefine __le__ and
  341. then the other operations will automatically follow suit.
  342. """
  343. def __le__(self, other):
  344. if not isinstance(other, Set):
  345. return NotImplemented
  346. if len(self) > len(other):
  347. return False
  348. for elem in self:
  349. if elem not in other:
  350. return False
  351. return True
  352. def __lt__(self, other):
  353. if not isinstance(other, Set):
  354. return NotImplemented
  355. return len(self) < len(other) and self.__le__(other)
  356. def __gt__(self, other):
  357. if not isinstance(other, Set):
  358. return NotImplemented
  359. return len(self) > len(other) and self.__ge__(other)
  360. def __ge__(self, other):
  361. if not isinstance(other, Set):
  362. return NotImplemented
  363. if len(self) < len(other):
  364. return False
  365. for elem in other:
  366. if elem not in self:
  367. return False
  368. return True
  369. def __eq__(self, other):
  370. if not isinstance(other, Set):
  371. return NotImplemented
  372. return len(self) == len(other) and self.__le__(other)
  373. def __ne__(self, other):
  374. return not (self == other)
  375. @classmethod
  376. def _from_iterable(cls, it):
  377. '''Construct an instance of the class from any iterable input.
  378. Must override this method if the class constructor signature
  379. does not accept an iterable for an input.
  380. '''
  381. return cls(it)
  382. def __and__(self, other):
  383. if not isinstance(other, Iterable):
  384. return NotImplemented
  385. return self._from_iterable(value for value in other if value in self)
  386. __rand__ = __and__
  387. def isdisjoint(self, other):
  388. 'Return True if two sets have a null intersection.'
  389. for value in other:
  390. if value in self:
  391. return False
  392. return True
  393. def __or__(self, other):
  394. if not isinstance(other, Iterable):
  395. return NotImplemented
  396. chain = (e for s in (self, other) for e in s)
  397. return self._from_iterable(chain)
  398. __ror__ = __or__
  399. def __sub__(self, other):
  400. if not isinstance(other, Set):
  401. if not isinstance(other, Iterable):
  402. return NotImplemented
  403. other = self._from_iterable(other)
  404. return self._from_iterable(value for value in self
  405. if value not in other)
  406. def __rsub__(self, other):
  407. if not isinstance(other, Set):
  408. if not isinstance(other, Iterable):
  409. return NotImplemented
  410. other = self._from_iterable(other)
  411. return self._from_iterable(value for value in other
  412. if value not in self)
  413. def __xor__(self, other):
  414. if not isinstance(other, Set):
  415. if not isinstance(other, Iterable):
  416. return NotImplemented
  417. other = self._from_iterable(other)
  418. return (self - other) | (other - self)
  419. __rxor__ = __xor__
  420. # Sets are not hashable by default, but subclasses can change this
  421. __hash__ = None
  422. def _hash(self):
  423. """Compute the hash value of a set.
  424. Note that we don't define __hash__: not all sets are hashable.
  425. But if you define a hashable set type, its __hash__ should
  426. call this function.
  427. This must be compatible __eq__.
  428. All sets ought to compare equal if they contain the same
  429. elements, regardless of how they are implemented, and
  430. regardless of the order of the elements; so there's not much
  431. freedom for __eq__ or __hash__. We match the algorithm used
  432. by the built-in frozenset type.
  433. """
  434. MAX = sys.maxint
  435. MASK = 2 * MAX + 1
  436. n = len(self)
  437. h = 1927868237 * (n + 1)
  438. h &= MASK
  439. for x in self:
  440. hx = hash(x)
  441. h ^= (hx ^ (hx << 16) ^ 89869747) * 3644798167
  442. h &= MASK
  443. h = h * 69069 + 907133923
  444. h &= MASK
  445. if h > MAX:
  446. h -= MASK + 1
  447. if h == -1:
  448. h = 590923713
  449. return h
  450. Set.register(frozenset)
  451. class MutableSet(Set):
  452. """A mutable set is a finite, iterable container.
  453. This class provides concrete generic implementations of all
  454. methods except for __contains__, __iter__, __len__,
  455. add(), and discard().
  456. To override the comparisons (presumably for speed, as the
  457. semantics are fixed), all you have to do is redefine __le__ and
  458. then the other operations will automatically follow suit.
  459. """
  460. @abstractmethod
  461. def add(self, value):
  462. """Add an element."""
  463. raise NotImplementedError
  464. @abstractmethod
  465. def discard(self, value):
  466. """Remove an element. Do not raise an exception if absent."""
  467. raise NotImplementedError
  468. def remove(self, value):
  469. """Remove an element. If not a member, raise a KeyError."""
  470. if value not in self:
  471. raise KeyError(value)
  472. self.discard(value)
  473. def pop(self):
  474. """Return the popped value. Raise KeyError if empty."""
  475. it = iter(self)
  476. try:
  477. value = next(it)
  478. except StopIteration:
  479. raise KeyError
  480. self.discard(value)
  481. return value
  482. def clear(self):
  483. """This is slow (creates N new iterators!) but effective."""
  484. try:
  485. while True:
  486. self.pop()
  487. except KeyError:
  488. pass
  489. def __ior__(self, it):
  490. for value in it:
  491. self.add(value)
  492. return self
  493. def __iand__(self, it):
  494. for value in (self - it):
  495. self.discard(value)
  496. return self
  497. def __ixor__(self, it):
  498. if it is self:
  499. self.clear()
  500. else:
  501. if not isinstance(it, Set):
  502. it = self._from_iterable(it)
  503. for value in it:
  504. if value in self:
  505. self.discard(value)
  506. else:
  507. self.add(value)
  508. return self
  509. def __isub__(self, it):
  510. if it is self:
  511. self.clear()
  512. else:
  513. for value in it:
  514. self.discard(value)
  515. return self
  516. MutableSet.register(set)
  517. ### MAPPINGS ###
  518. class Mapping(Sized, Iterable, Container):
  519. """A Mapping is a generic container for associating key/value
  520. pairs.
  521. This class provides concrete generic implementations of all
  522. methods except for __getitem__, __iter__, and __len__.
  523. """
  524. @abstractmethod
  525. def __getitem__(self, key):
  526. raise KeyError
  527. def get(self, key, default=None):
  528. 'D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.'
  529. try:
  530. return self[key]
  531. except KeyError:
  532. return default
  533. def __contains__(self, key):
  534. try:
  535. self[key]
  536. except KeyError:
  537. return False
  538. else:
  539. return True
  540. def iterkeys(self):
  541. 'D.iterkeys() -> an iterator over the keys of D'
  542. return iter(self)
  543. def itervalues(self):
  544. 'D.itervalues() -> an iterator over the values of D'
  545. for key in self:
  546. yield self[key]
  547. def iteritems(self):
  548. 'D.iteritems() -> an iterator over the (key, value) items of D'
  549. for key in self:
  550. yield (key, self[key])
  551. def keys(self):
  552. "D.keys() -> list of D's keys"
  553. return list(self)
  554. def items(self):
  555. "D.items() -> list of D's (key, value) pairs, as 2-tuples"
  556. return [(key, self[key]) for key in self]
  557. def values(self):
  558. "D.values() -> list of D's values"
  559. return [self[key] for key in self]
  560. # Mappings are not hashable by default, but subclasses can change this
  561. __hash__ = None
  562. def __eq__(self, other):
  563. if not isinstance(other, Mapping):
  564. return NotImplemented
  565. return dict(self.items()) == dict(other.items())
  566. def __ne__(self, other):
  567. return not (self == other)
  568. class MappingView(Sized):
  569. def __init__(self, mapping):
  570. self._mapping = mapping
  571. def __len__(self):
  572. return len(self._mapping)
  573. def __repr__(self):
  574. return '{0.__class__.__name__}({0._mapping!r})'.format(self)
  575. class KeysView(MappingView, Set):
  576. @classmethod
  577. def _from_iterable(self, it):
  578. return set(it)
  579. def __contains__(self, key):
  580. return key in self._mapping
  581. def __iter__(self):
  582. for key in self._mapping:
  583. yield key
  584. class ItemsView(MappingView, Set):
  585. @classmethod
  586. def _from_iterable(self, it):
  587. return set(it)
  588. def __contains__(self, item):
  589. key, value = item
  590. try:
  591. v = self._mapping[key]
  592. except KeyError:
  593. return False
  594. else:
  595. return v == value
  596. def __iter__(self):
  597. for key in self._mapping:
  598. yield (key, self._mapping[key])
  599. class ValuesView(MappingView):
  600. def __contains__(self, value):
  601. for key in self._mapping:
  602. if value == self._mapping[key]:
  603. return True
  604. return False
  605. def __iter__(self):
  606. for key in self._mapping:
  607. yield self._mapping[key]
  608. class MutableMapping(Mapping):
  609. """A MutableMapping is a generic container for associating
  610. key/value pairs.
  611. This class provides concrete generic implementations of all
  612. methods except for __getitem__, __setitem__, __delitem__,
  613. __iter__, and __len__.
  614. """
  615. @abstractmethod
  616. def __setitem__(self, key, value):
  617. raise KeyError
  618. @abstractmethod
  619. def __delitem__(self, key):
  620. raise KeyError
  621. __marker = object()
  622. def pop(self, key, default=__marker):
  623. '''D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
  624. If key is not found, d is returned if given, otherwise KeyError is raised.
  625. '''
  626. try:
  627. value = self[key]
  628. except KeyError:
  629. if default is self.__marker:
  630. raise
  631. return default
  632. else:
  633. del self[key]
  634. return value
  635. def popitem(self):
  636. '''D.popitem() -> (k, v), remove and return some (key, value) pair
  637. as a 2-tuple; but raise KeyError if D is empty.
  638. '''
  639. try:
  640. key = next(iter(self))
  641. except StopIteration:
  642. raise KeyError
  643. value = self[key]
  644. del self[key]
  645. return key, value
  646. def clear(self):
  647. 'D.clear() -> None. Remove all items from D.'
  648. try:
  649. while True:
  650. self.popitem()
  651. except KeyError:
  652. pass
  653. def update(*args, **kwds):
  654. ''' D.update([E, ]**F) -> None. Update D from mapping/iterable E and F.
  655. If E present and has a .keys() method, does: for k in E: D[k] = E[k]
  656. If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
  657. In either case, this is followed by: for k, v in F.items(): D[k] = v
  658. '''
  659. if len(args) > 2:
  660. raise TypeError("update() takes at most 2 positional "
  661. "arguments ({} given)".format(len(args)))
  662. elif not args:
  663. raise TypeError("update() takes at least 1 argument (0 given)")
  664. self = args[0]
  665. other = args[1] if len(args) >= 2 else ()
  666. if isinstance(other, Mapping):
  667. for key in other:
  668. self[key] = other[key]
  669. elif hasattr(other, "keys"):
  670. for key in other.keys():
  671. self[key] = other[key]
  672. else:
  673. for key, value in other:
  674. self[key] = value
  675. for key, value in kwds.items():
  676. self[key] = value
  677. def setdefault(self, key, default=None):
  678. 'D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D'
  679. try:
  680. return self[key]
  681. except KeyError:
  682. self[key] = default
  683. return default
  684. MutableMapping.register(dict)
  685. ### SEQUENCES ###
  686. class Sequence(Sized, Iterable, Container):
  687. """All the operations on a read-only sequence.
  688. Concrete subclasses must override __new__ or __init__,
  689. __getitem__, and __len__.
  690. """
  691. @abstractmethod
  692. def __getitem__(self, index):
  693. raise IndexError
  694. def __iter__(self):
  695. i = 0
  696. try:
  697. while True:
  698. v = self[i]
  699. yield v
  700. i += 1
  701. except IndexError:
  702. return
  703. def __contains__(self, value):
  704. for v in self:
  705. if v == value:
  706. return True
  707. return False
  708. def __reversed__(self):
  709. for i in reversed(range(len(self))):
  710. yield self[i]
  711. def index(self, value):
  712. '''S.index(value) -> integer -- return first index of value.
  713. Raises ValueError if the value is not present.
  714. '''
  715. for i, v in enumerate(self):
  716. if v == value:
  717. return i
  718. raise ValueError
  719. def count(self, value):
  720. 'S.count(value) -> integer -- return number of occurrences of value'
  721. return sum(1 for v in self if v == value)
  722. Sequence.register(tuple)
  723. Sequence.register(basestring)
  724. Sequence.register(buffer)
  725. Sequence.register(xrange)
  726. class MutableSequence(Sequence):
  727. """All the operations on a read-only sequence.
  728. Concrete subclasses must provide __new__ or __init__,
  729. __getitem__, __setitem__, __delitem__, __len__, and insert().
  730. """
  731. @abstractmethod
  732. def __setitem__(self, index, value):
  733. raise IndexError
  734. @abstractmethod
  735. def __delitem__(self, index):
  736. raise IndexError
  737. @abstractmethod
  738. def insert(self, index, value):
  739. 'S.insert(index, object) -- insert object before index'
  740. raise IndexError
  741. def append(self, value):
  742. 'S.append(object) -- append object to the end of the sequence'
  743. self.insert(len(self), value)
  744. def reverse(self):
  745. 'S.reverse() -- reverse *IN PLACE*'
  746. n = len(self)
  747. for i in range(n//2):
  748. self[i], self[n-i-1] = self[n-i-1], self[i]
  749. def extend(self, values):
  750. 'S.extend(iterable) -- extend sequence by appending elements from the iterable'
  751. for v in values:
  752. self.append(v)
  753. def pop(self, index=-1):
  754. '''S.pop([index]) -> item -- remove and return item at index (default last).
  755. Raise IndexError if list is empty or index is out of range.
  756. '''
  757. v = self[index]
  758. del self[index]
  759. return v
  760. def remove(self, value):
  761. '''S.remove(value) -- remove first occurrence of value.
  762. Raise ValueError if the value is not present.
  763. '''
  764. del self[self.index(value)]
  765. def __iadd__(self, values):
  766. self.extend(values)
  767. return self
  768. MutableSequence.register(list)