You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

datastructures.py 9.0 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. import copy
  2. from collections import OrderedDict
  3. from django.utils import six
  4. class OrderedSet(object):
  5. """
  6. A set which keeps the ordering of the inserted items.
  7. Currently backs onto OrderedDict.
  8. """
  9. def __init__(self, iterable=None):
  10. self.dict = OrderedDict(((x, None) for x in iterable) if iterable else [])
  11. def add(self, item):
  12. self.dict[item] = None
  13. def remove(self, item):
  14. del self.dict[item]
  15. def discard(self, item):
  16. try:
  17. self.remove(item)
  18. except KeyError:
  19. pass
  20. def __iter__(self):
  21. return iter(self.dict.keys())
  22. def __contains__(self, item):
  23. return item in self.dict
  24. def __bool__(self):
  25. return bool(self.dict)
  26. def __nonzero__(self): # Python 2 compatibility
  27. return type(self).__bool__(self)
  28. def __len__(self):
  29. return len(self.dict)
  30. class MultiValueDictKeyError(KeyError):
  31. pass
  32. class MultiValueDict(dict):
  33. """
  34. A subclass of dictionary customized to handle multiple values for the
  35. same key.
  36. >>> d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']})
  37. >>> d['name']
  38. 'Simon'
  39. >>> d.getlist('name')
  40. ['Adrian', 'Simon']
  41. >>> d.getlist('doesnotexist')
  42. []
  43. >>> d.getlist('doesnotexist', ['Adrian', 'Simon'])
  44. ['Adrian', 'Simon']
  45. >>> d.get('lastname', 'nonexistent')
  46. 'nonexistent'
  47. >>> d.setlist('lastname', ['Holovaty', 'Willison'])
  48. This class exists to solve the irritating problem raised by cgi.parse_qs,
  49. which returns a list for every key, even though most Web forms submit
  50. single name-value pairs.
  51. """
  52. def __init__(self, key_to_list_mapping=()):
  53. super(MultiValueDict, self).__init__(key_to_list_mapping)
  54. def __repr__(self):
  55. return "<%s: %s>" % (self.__class__.__name__,
  56. super(MultiValueDict, self).__repr__())
  57. def __getitem__(self, key):
  58. """
  59. Returns the last data value for this key, or [] if it's an empty list;
  60. raises KeyError if not found.
  61. """
  62. try:
  63. list_ = super(MultiValueDict, self).__getitem__(key)
  64. except KeyError:
  65. raise MultiValueDictKeyError(repr(key))
  66. try:
  67. return list_[-1]
  68. except IndexError:
  69. return []
  70. def __setitem__(self, key, value):
  71. super(MultiValueDict, self).__setitem__(key, [value])
  72. def __copy__(self):
  73. return self.__class__([
  74. (k, v[:])
  75. for k, v in self.lists()
  76. ])
  77. def __deepcopy__(self, memo=None):
  78. if memo is None:
  79. memo = {}
  80. result = self.__class__()
  81. memo[id(self)] = result
  82. for key, value in dict.items(self):
  83. dict.__setitem__(result, copy.deepcopy(key, memo),
  84. copy.deepcopy(value, memo))
  85. return result
  86. def __getstate__(self):
  87. obj_dict = self.__dict__.copy()
  88. obj_dict['_data'] = {k: self.getlist(k) for k in self}
  89. return obj_dict
  90. def __setstate__(self, obj_dict):
  91. data = obj_dict.pop('_data', {})
  92. for k, v in data.items():
  93. self.setlist(k, v)
  94. self.__dict__.update(obj_dict)
  95. def get(self, key, default=None):
  96. """
  97. Returns the last data value for the passed key. If key doesn't exist
  98. or value is an empty list, then default is returned.
  99. """
  100. try:
  101. val = self[key]
  102. except KeyError:
  103. return default
  104. if val == []:
  105. return default
  106. return val
  107. def getlist(self, key, default=None):
  108. """
  109. Returns the list of values for the passed key. If key doesn't exist,
  110. then a default value is returned.
  111. """
  112. try:
  113. return super(MultiValueDict, self).__getitem__(key)
  114. except KeyError:
  115. if default is None:
  116. return []
  117. return default
  118. def setlist(self, key, list_):
  119. super(MultiValueDict, self).__setitem__(key, list_)
  120. def setdefault(self, key, default=None):
  121. if key not in self:
  122. self[key] = default
  123. # Do not return default here because __setitem__() may store
  124. # another value -- QueryDict.__setitem__() does. Look it up.
  125. return self[key]
  126. def setlistdefault(self, key, default_list=None):
  127. if key not in self:
  128. if default_list is None:
  129. default_list = []
  130. self.setlist(key, default_list)
  131. # Do not return default_list here because setlist() may store
  132. # another value -- QueryDict.setlist() does. Look it up.
  133. return self.getlist(key)
  134. def appendlist(self, key, value):
  135. """Appends an item to the internal list associated with key."""
  136. self.setlistdefault(key).append(value)
  137. def _iteritems(self):
  138. """
  139. Yields (key, value) pairs, where value is the last item in the list
  140. associated with the key.
  141. """
  142. for key in self:
  143. yield key, self[key]
  144. def _iterlists(self):
  145. """Yields (key, list) pairs."""
  146. return six.iteritems(super(MultiValueDict, self))
  147. def _itervalues(self):
  148. """Yield the last value on every key list."""
  149. for key in self:
  150. yield self[key]
  151. if six.PY3:
  152. items = _iteritems
  153. lists = _iterlists
  154. values = _itervalues
  155. else:
  156. iteritems = _iteritems
  157. iterlists = _iterlists
  158. itervalues = _itervalues
  159. def items(self):
  160. return list(self.iteritems())
  161. def lists(self):
  162. return list(self.iterlists())
  163. def values(self):
  164. return list(self.itervalues())
  165. def copy(self):
  166. """Returns a shallow copy of this object."""
  167. return copy.copy(self)
  168. def update(self, *args, **kwargs):
  169. """
  170. update() extends rather than replaces existing key lists.
  171. Also accepts keyword args.
  172. """
  173. if len(args) > 1:
  174. raise TypeError("update expected at most 1 arguments, got %d" % len(args))
  175. if args:
  176. other_dict = args[0]
  177. if isinstance(other_dict, MultiValueDict):
  178. for key, value_list in other_dict.lists():
  179. self.setlistdefault(key).extend(value_list)
  180. else:
  181. try:
  182. for key, value in other_dict.items():
  183. self.setlistdefault(key).append(value)
  184. except TypeError:
  185. raise ValueError("MultiValueDict.update() takes either a MultiValueDict or dictionary")
  186. for key, value in six.iteritems(kwargs):
  187. self.setlistdefault(key).append(value)
  188. def dict(self):
  189. """
  190. Returns current object as a dict with singular values.
  191. """
  192. return {key: self[key] for key in self}
  193. class ImmutableList(tuple):
  194. """
  195. A tuple-like object that raises useful errors when it is asked to mutate.
  196. Example::
  197. >>> a = ImmutableList(range(5), warning="You cannot mutate this.")
  198. >>> a[3] = '4'
  199. Traceback (most recent call last):
  200. ...
  201. AttributeError: You cannot mutate this.
  202. """
  203. def __new__(cls, *args, **kwargs):
  204. if 'warning' in kwargs:
  205. warning = kwargs['warning']
  206. del kwargs['warning']
  207. else:
  208. warning = 'ImmutableList object is immutable.'
  209. self = tuple.__new__(cls, *args, **kwargs)
  210. self.warning = warning
  211. return self
  212. def complain(self, *wargs, **kwargs):
  213. if isinstance(self.warning, Exception):
  214. raise self.warning
  215. else:
  216. raise AttributeError(self.warning)
  217. # All list mutation functions complain.
  218. __delitem__ = complain
  219. __delslice__ = complain
  220. __iadd__ = complain
  221. __imul__ = complain
  222. __setitem__ = complain
  223. __setslice__ = complain
  224. append = complain
  225. extend = complain
  226. insert = complain
  227. pop = complain
  228. remove = complain
  229. sort = complain
  230. reverse = complain
  231. class DictWrapper(dict):
  232. """
  233. Wraps accesses to a dictionary so that certain values (those starting with
  234. the specified prefix) are passed through a function before being returned.
  235. The prefix is removed before looking up the real value.
  236. Used by the SQL construction code to ensure that values are correctly
  237. quoted before being used.
  238. """
  239. def __init__(self, data, func, prefix):
  240. super(DictWrapper, self).__init__(data)
  241. self.func = func
  242. self.prefix = prefix
  243. def __getitem__(self, key):
  244. """
  245. Retrieves the real value after stripping the prefix string (if
  246. present). If the prefix is present, pass the value through self.func
  247. before returning, otherwise return the raw value.
  248. """
  249. if key.startswith(self.prefix):
  250. use_func = True
  251. key = key[len(self.prefix):]
  252. else:
  253. use_func = False
  254. value = super(DictWrapper, self).__getitem__(key)
  255. if use_func:
  256. return self.func(value)
  257. return value