odict.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. # markdown is released under the BSD license
  2. # Copyright 2007, 2008 The Python Markdown Project (v. 1.7 and later)
  3. # Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b)
  4. # Copyright 2004 Manfred Stienstra (the original version)
  5. #
  6. # All rights reserved.
  7. #
  8. # Redistribution and use in source and binary forms, with or without
  9. # modification, are permitted provided that the following conditions are met:
  10. #
  11. # * Redistributions of source code must retain the above copyright
  12. # notice, this list of conditions and the following disclaimer.
  13. # * Redistributions in binary form must reproduce the above copyright
  14. # notice, this list of conditions and the following disclaimer in the
  15. # documentation and/or other materials provided with the distribution.
  16. # * Neither the name of the <organization> nor the
  17. # names of its contributors may be used to endorse or promote products
  18. # derived from this software without specific prior written permission.
  19. #
  20. # THIS SOFTWARE IS PROVIDED BY THE PYTHON MARKDOWN PROJECT ''AS IS'' AND ANY
  21. # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  22. # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  23. # DISCLAIMED. IN NO EVENT SHALL ANY CONTRIBUTORS TO THE PYTHON MARKDOWN PROJECT
  24. # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  25. # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  26. # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  27. # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  28. # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  29. # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  30. # POSSIBILITY OF SUCH DAMAGE.
  31. from __future__ import unicode_literals
  32. from __future__ import absolute_import
  33. from . import util
  34. from copy import deepcopy
  35. def iteritems_compat(d):
  36. """Return an iterator over the (key, value) pairs of a dictionary.
  37. Copied from `six` module."""
  38. return iter(getattr(d, _iteritems)())
  39. class OrderedDict(dict):
  40. """
  41. A dictionary that keeps its keys in the order in which they're inserted.
  42. Copied from Django's SortedDict with some modifications.
  43. """
  44. def __new__(cls, *args, **kwargs):
  45. instance = super(OrderedDict, cls).__new__(cls, *args, **kwargs)
  46. instance.keyOrder = []
  47. return instance
  48. def __init__(self, data=None):
  49. if data is None or isinstance(data, dict):
  50. data = data or []
  51. super(OrderedDict, self).__init__(data)
  52. self.keyOrder = list(data) if data else []
  53. else:
  54. super(OrderedDict, self).__init__()
  55. super_set = super(OrderedDict, self).__setitem__
  56. for key, value in data:
  57. # Take the ordering from first key
  58. if key not in self:
  59. self.keyOrder.append(key)
  60. # But override with last value in data (dict() does this)
  61. super_set(key, value)
  62. def __deepcopy__(self, memo):
  63. return self.__class__([(key, deepcopy(value, memo))
  64. for key, value in self.items()])
  65. def __copy__(self):
  66. # The Python's default copy implementation will alter the state
  67. # of self. The reason for this seems complex but is likely related to
  68. # subclassing dict.
  69. return self.copy()
  70. def __setitem__(self, key, value):
  71. if key not in self:
  72. self.keyOrder.append(key)
  73. super(OrderedDict, self).__setitem__(key, value)
  74. def __delitem__(self, key):
  75. super(OrderedDict, self).__delitem__(key)
  76. self.keyOrder.remove(key)
  77. def __iter__(self):
  78. return iter(self.keyOrder)
  79. def __reversed__(self):
  80. return reversed(self.keyOrder)
  81. def pop(self, k, *args):
  82. result = super(OrderedDict, self).pop(k, *args)
  83. try:
  84. self.keyOrder.remove(k)
  85. except ValueError:
  86. # Key wasn't in the dictionary in the first place. No problem.
  87. pass
  88. return result
  89. def popitem(self):
  90. result = super(OrderedDict, self).popitem()
  91. self.keyOrder.remove(result[0])
  92. return result
  93. def _iteritems(self):
  94. for key in self.keyOrder:
  95. yield key, self[key]
  96. def _iterkeys(self):
  97. for key in self.keyOrder:
  98. yield key
  99. def _itervalues(self):
  100. for key in self.keyOrder:
  101. yield self[key]
  102. if util.PY3:
  103. items = _iteritems
  104. keys = _iterkeys
  105. values = _itervalues
  106. else:
  107. iteritems = _iteritems
  108. iterkeys = _iterkeys
  109. itervalues = _itervalues
  110. def items(self):
  111. return [(k, self[k]) for k in self.keyOrder]
  112. def keys(self):
  113. return self.keyOrder[:]
  114. def values(self):
  115. return [self[k] for k in self.keyOrder]
  116. def update(self, dict_):
  117. for k, v in iteritems_compat(dict_):
  118. self[k] = v
  119. def setdefault(self, key, default):
  120. if key not in self:
  121. self.keyOrder.append(key)
  122. return super(OrderedDict, self).setdefault(key, default)
  123. def value_for_index(self, index):
  124. """Returns the value of the item at the given zero-based index."""
  125. return self[self.keyOrder[index]]
  126. def insert(self, index, key, value):
  127. """Inserts the key, value pair before the item with the given index."""
  128. if key in self.keyOrder:
  129. n = self.keyOrder.index(key)
  130. del self.keyOrder[n]
  131. if n < index:
  132. index -= 1
  133. self.keyOrder.insert(index, key)
  134. super(OrderedDict, self).__setitem__(key, value)
  135. def copy(self):
  136. """Returns a copy of this object."""
  137. # This way of initializing the copy means it works for subclasses, too.
  138. return self.__class__(self)
  139. def __repr__(self):
  140. """
  141. Replaces the normal dict.__repr__ with a version that returns the keys
  142. in their Ordered order.
  143. """
  144. return '{%s}' % ', '.join(['%r: %r' % (k, v) for k, v in iteritems_compat(self)])
  145. def clear(self):
  146. super(OrderedDict, self).clear()
  147. self.keyOrder = []
  148. def index(self, key):
  149. """ Return the index of a given key. """
  150. try:
  151. return self.keyOrder.index(key)
  152. except ValueError:
  153. raise ValueError("Element '%s' was not found in OrderedDict" % key)
  154. def index_for_location(self, location):
  155. """ Return index or None for a given location. """
  156. if location == '_begin':
  157. i = 0
  158. elif location == '_end':
  159. i = None
  160. elif location.startswith('<') or location.startswith('>'):
  161. i = self.index(location[1:])
  162. if location.startswith('>'):
  163. if i >= len(self):
  164. # last item
  165. i = None
  166. else:
  167. i += 1
  168. else:
  169. raise ValueError('Not a valid location: "%s". Location key '
  170. 'must start with a ">" or "<".' % location)
  171. return i
  172. def add(self, key, value, location):
  173. """ Insert by key location. """
  174. i = self.index_for_location(location)
  175. if i is not None:
  176. self.insert(i, key, value)
  177. else:
  178. self.__setitem__(key, value)
  179. def link(self, key, location):
  180. """ Change location of an existing item. """
  181. n = self.keyOrder.index(key)
  182. del self.keyOrder[n]
  183. try:
  184. i = self.index_for_location(location)
  185. if i is not None:
  186. self.keyOrder.insert(i, key)
  187. else:
  188. self.keyOrder.append(key)
  189. except Exception as e:
  190. # restore to prevent data loss and reraise
  191. self.keyOrder.insert(n, key)
  192. raise e