_compat.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. # _compat.py -- For dealing with python2.4 oddness
  2. # Copyright (C) 2008 Canonical Ltd.
  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.
  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 pypy.
  23. # 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 dictionaries.
  39. # The internal self.__map dictionary maps keys to links in a doubly linked list.
  40. # The circular doubly linked list starts and ends with a sentinel element.
  41. # The sentinel element never gets deleted (this simplifies the algorithm).
  42. # Each link is stored as a list of length three: [PREV, NEXT, KEY].
  43. def __init__(self, *args, **kwds):
  44. '''Initialize an ordered dictionary. Signature is the same as for
  45. regular dictionaries, but keyword arguments are not recommended
  46. because their insertion order is arbitrary.
  47. '''
  48. if len(args) > 1:
  49. raise TypeError('expected at most 1 arguments, got %d' % len(args))
  50. try:
  51. self.__root
  52. except AttributeError:
  53. self.__root = root = [] # sentinel node
  54. root[:] = [root, root, None]
  55. self.__map = {}
  56. self.__update(*args, **kwds)
  57. def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
  58. 'od.__setitem__(i, y) <==> od[i]=y'
  59. # Setting a new item creates a new link which goes at the end of the linked
  60. # list, and the inherited dictionary is updated with the new key/value pair.
  61. if key not in self:
  62. root = self.__root
  63. last = root[0]
  64. last[1] = root[0] = self.__map[key] = [last, root, key]
  65. dict_setitem(self, key, value)
  66. def __delitem__(self, key, dict_delitem=dict.__delitem__):
  67. 'od.__delitem__(y) <==> del od[y]'
  68. # Deleting an existing item uses self.__map to find the link which is
  69. # then removed by updating the links in the predecessor and successor nodes.
  70. dict_delitem(self, key)
  71. link_prev, link_next, key = self.__map.pop(key)
  72. link_prev[1] = link_next
  73. link_next[0] = link_prev
  74. def __iter__(self):
  75. 'od.__iter__() <==> iter(od)'
  76. root = self.__root
  77. curr = root[1]
  78. while curr is not root:
  79. yield curr[2]
  80. curr = curr[1]
  81. def __reversed__(self):
  82. 'od.__reversed__() <==> reversed(od)'
  83. root = self.__root
  84. curr = root[0]
  85. while curr is not root:
  86. yield curr[2]
  87. curr = curr[0]
  88. def clear(self):
  89. 'od.clear() -> None. Remove all items from od.'
  90. try:
  91. for node in self.__map.itervalues():
  92. del node[:]
  93. root = self.__root
  94. root[:] = [root, root, None]
  95. self.__map.clear()
  96. except AttributeError:
  97. pass
  98. dict.clear(self)
  99. def popitem(self, last=True):
  100. """od.popitem() -> (k, v), return and remove a (key, value) pair.
  101. Pairs are returned in LIFO order if last is true or FIFO order if false.
  102. """
  103. if not self:
  104. raise KeyError('dictionary is empty')
  105. root = self.__root
  106. if last:
  107. link = root[0]
  108. link_prev = link[0]
  109. link_prev[1] = root
  110. root[0] = link_prev
  111. else:
  112. link = root[1]
  113. link_next = link[1]
  114. root[1] = link_next
  115. link_next[0] = root
  116. key = link[2]
  117. del self.__map[key]
  118. value = dict.pop(self, key)
  119. return key, value
  120. # -- the following methods do not depend on the internal structure --
  121. def keys(self):
  122. """'od.keys() -> list of keys in od"""
  123. return list(self)
  124. def values(self):
  125. """od.values() -> list of values in od"""
  126. return [self[key] for key in self]
  127. def items(self):
  128. """od.items() -> list of (key, value) pairs in od"""
  129. return [(key, self[key]) for key in self]
  130. def iterkeys(self):
  131. """od.iterkeys() -> an iterator over the keys in od"""
  132. return iter(self)
  133. def itervalues(self):
  134. """od.itervalues -> an iterator over the values in od"""
  135. for k in self:
  136. yield self[k]
  137. def iteritems(self):
  138. """od.iteritems -> an iterator over the (key, value) items in od"""
  139. for k in self:
  140. yield (k, self[k])
  141. def update(*args, **kwds):
  142. """od.update(E, F) -> None. Update od from dict/iterable E and F.
  143. If E is a dict instance, does: for k in E: od[k] = E[k]
  144. If E has a .keys() method, does: for k in E.keys(): od[k] = E[k]
  145. Or if E is an iterable of items, does: for k, v in E: od[k] = v
  146. In either case, this is followed by: for k, v in F.items(): od[k] = v
  147. """
  148. if len(args) > 2:
  149. raise TypeError('update() takes at most 2 positional '
  150. 'arguments (%d given)' % (len(args),))
  151. elif not args:
  152. raise TypeError('update() takes at least 1 argument (0 given)')
  153. self = args[0]
  154. # Make progressively weaker assumptions about "other"
  155. other = ()
  156. if len(args) == 2:
  157. other = args[1]
  158. if isinstance(other, dict):
  159. for key in other:
  160. self[key] = other[key]
  161. elif hasattr(other, 'keys'):
  162. for key in other.keys():
  163. self[key] = other[key]
  164. else:
  165. for key, value in other:
  166. self[key] = value
  167. for key, value in kwds.items():
  168. self[key] = value
  169. __update = update # let subclasses override update without breaking __init__
  170. __marker = object()
  171. def pop(self, key, default=__marker):
  172. """od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
  173. If key is not found, d is returned if given, otherwise KeyError is raised.
  174. """
  175. if key in self:
  176. result = self[key]
  177. del self[key]
  178. return result
  179. if default is self.__marker:
  180. raise KeyError(key)
  181. return default
  182. def setdefault(self, key, default=None):
  183. 'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
  184. if key in self:
  185. return self[key]
  186. self[key] = default
  187. return default
  188. def __repr__(self, _repr_running={}):
  189. 'od.__repr__() <==> repr(od)'
  190. call_key = id(self), _get_ident()
  191. if call_key in _repr_running:
  192. return '...'
  193. _repr_running[call_key] = 1
  194. try:
  195. if not self:
  196. return '%s()' % (self.__class__.__name__,)
  197. return '%s(%r)' % (self.__class__.__name__, self.items())
  198. finally:
  199. del _repr_running[call_key]
  200. def __reduce__(self):
  201. 'Return state information for pickling'
  202. items = [[k, self[k]] for k in self]
  203. inst_dict = vars(self).copy()
  204. for k in vars(OrderedDict()):
  205. inst_dict.pop(k, None)
  206. if inst_dict:
  207. return (self.__class__, (items,), inst_dict)
  208. return self.__class__, (items,)
  209. def copy(self):
  210. 'od.copy() -> a shallow copy of od'
  211. return self.__class__(self)
  212. @classmethod
  213. def fromkeys(cls, iterable, value=None):
  214. '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
  215. and values equal to v (which defaults to None).
  216. '''
  217. d = cls()
  218. for key in iterable:
  219. d[key] = value
  220. return d
  221. def __eq__(self, other):
  222. '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
  223. while comparison to a regular mapping is order-insensitive.
  224. '''
  225. if isinstance(other, OrderedDict):
  226. return len(self)==len(other) and self.items() == other.items()
  227. return dict.__eq__(self, other)
  228. def __ne__(self, other):
  229. return not self == other
  230. # -- the following methods are only used in Python 2.7 --
  231. def viewkeys(self):
  232. "od.viewkeys() -> a set-like object providing a view on od's keys"
  233. return KeysView(self)
  234. def viewvalues(self):
  235. "od.viewvalues() -> an object providing a view on od's values"
  236. return ValuesView(self)
  237. def viewitems(self):
  238. "od.viewitems() -> a set-like object providing a view on od's items"
  239. return ItemsView(self)