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 10.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. import copy
  2. from collections import OrderedDict
  3. from collections.abc import Mapping
  4. class OrderedSet:
  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.fromkeys(iterable or ())
  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)
  22. def __contains__(self, item):
  23. return item in self.dict
  24. def __bool__(self):
  25. return bool(self.dict)
  26. def __len__(self):
  27. return len(self.dict)
  28. class MultiValueDictKeyError(KeyError):
  29. pass
  30. class MultiValueDict(dict):
  31. """
  32. A subclass of dictionary customized to handle multiple values for the
  33. same key.
  34. >>> d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']})
  35. >>> d['name']
  36. 'Simon'
  37. >>> d.getlist('name')
  38. ['Adrian', 'Simon']
  39. >>> d.getlist('doesnotexist')
  40. []
  41. >>> d.getlist('doesnotexist', ['Adrian', 'Simon'])
  42. ['Adrian', 'Simon']
  43. >>> d.get('lastname', 'nonexistent')
  44. 'nonexistent'
  45. >>> d.setlist('lastname', ['Holovaty', 'Willison'])
  46. This class exists to solve the irritating problem raised by cgi.parse_qs,
  47. which returns a list for every key, even though most Web forms submit
  48. single name-value pairs.
  49. """
  50. def __init__(self, key_to_list_mapping=()):
  51. super().__init__(key_to_list_mapping)
  52. def __repr__(self):
  53. return "<%s: %s>" % (self.__class__.__name__, super().__repr__())
  54. def __getitem__(self, key):
  55. """
  56. Return the last data value for this key, or [] if it's an empty list;
  57. raise KeyError if not found.
  58. """
  59. try:
  60. list_ = super().__getitem__(key)
  61. except KeyError:
  62. raise MultiValueDictKeyError(key)
  63. try:
  64. return list_[-1]
  65. except IndexError:
  66. return []
  67. def __setitem__(self, key, value):
  68. super().__setitem__(key, [value])
  69. def __copy__(self):
  70. return self.__class__([
  71. (k, v[:])
  72. for k, v in self.lists()
  73. ])
  74. def __deepcopy__(self, memo):
  75. result = self.__class__()
  76. memo[id(self)] = result
  77. for key, value in dict.items(self):
  78. dict.__setitem__(result, copy.deepcopy(key, memo),
  79. copy.deepcopy(value, memo))
  80. return result
  81. def __getstate__(self):
  82. return {**self.__dict__, '_data': {k: self._getlist(k) for k in self}}
  83. def __setstate__(self, obj_dict):
  84. data = obj_dict.pop('_data', {})
  85. for k, v in data.items():
  86. self.setlist(k, v)
  87. self.__dict__.update(obj_dict)
  88. def get(self, key, default=None):
  89. """
  90. Return the last data value for the passed key. If key doesn't exist
  91. or value is an empty list, return `default`.
  92. """
  93. try:
  94. val = self[key]
  95. except KeyError:
  96. return default
  97. if val == []:
  98. return default
  99. return val
  100. def _getlist(self, key, default=None, force_list=False):
  101. """
  102. Return a list of values for the key.
  103. Used internally to manipulate values list. If force_list is True,
  104. return a new copy of values.
  105. """
  106. try:
  107. values = super().__getitem__(key)
  108. except KeyError:
  109. if default is None:
  110. return []
  111. return default
  112. else:
  113. if force_list:
  114. values = list(values) if values is not None else None
  115. return values
  116. def getlist(self, key, default=None):
  117. """
  118. Return the list of values for the key. If key doesn't exist, return a
  119. default value.
  120. """
  121. return self._getlist(key, default, force_list=True)
  122. def setlist(self, key, list_):
  123. super().__setitem__(key, list_)
  124. def setdefault(self, key, default=None):
  125. if key not in self:
  126. self[key] = default
  127. # Do not return default here because __setitem__() may store
  128. # another value -- QueryDict.__setitem__() does. Look it up.
  129. return self[key]
  130. def setlistdefault(self, key, default_list=None):
  131. if key not in self:
  132. if default_list is None:
  133. default_list = []
  134. self.setlist(key, default_list)
  135. # Do not return default_list here because setlist() may store
  136. # another value -- QueryDict.setlist() does. Look it up.
  137. return self._getlist(key)
  138. def appendlist(self, key, value):
  139. """Append an item to the internal list associated with key."""
  140. self.setlistdefault(key).append(value)
  141. def items(self):
  142. """
  143. Yield (key, value) pairs, where value is the last item in the list
  144. associated with the key.
  145. """
  146. for key in self:
  147. yield key, self[key]
  148. def lists(self):
  149. """Yield (key, list) pairs."""
  150. return iter(super().items())
  151. def values(self):
  152. """Yield the last value on every key list."""
  153. for key in self:
  154. yield self[key]
  155. def copy(self):
  156. """Return a shallow copy of this object."""
  157. return copy.copy(self)
  158. def update(self, *args, **kwargs):
  159. """Extend rather than replace existing key lists."""
  160. if len(args) > 1:
  161. raise TypeError("update expected at most 1 argument, got %d" % len(args))
  162. if args:
  163. other_dict = args[0]
  164. if isinstance(other_dict, MultiValueDict):
  165. for key, value_list in other_dict.lists():
  166. self.setlistdefault(key).extend(value_list)
  167. else:
  168. try:
  169. for key, value in other_dict.items():
  170. self.setlistdefault(key).append(value)
  171. except TypeError:
  172. raise ValueError("MultiValueDict.update() takes either a MultiValueDict or dictionary")
  173. for key, value in kwargs.items():
  174. self.setlistdefault(key).append(value)
  175. def dict(self):
  176. """Return current object as a dict with singular values."""
  177. return {key: self[key] for key in self}
  178. class ImmutableList(tuple):
  179. """
  180. A tuple-like object that raises useful errors when it is asked to mutate.
  181. Example::
  182. >>> a = ImmutableList(range(5), warning="You cannot mutate this.")
  183. >>> a[3] = '4'
  184. Traceback (most recent call last):
  185. ...
  186. AttributeError: You cannot mutate this.
  187. """
  188. def __new__(cls, *args, warning='ImmutableList object is immutable.', **kwargs):
  189. self = tuple.__new__(cls, *args, **kwargs)
  190. self.warning = warning
  191. return self
  192. def complain(self, *wargs, **kwargs):
  193. if isinstance(self.warning, Exception):
  194. raise self.warning
  195. else:
  196. raise AttributeError(self.warning)
  197. # All list mutation functions complain.
  198. __delitem__ = complain
  199. __delslice__ = complain
  200. __iadd__ = complain
  201. __imul__ = complain
  202. __setitem__ = complain
  203. __setslice__ = complain
  204. append = complain
  205. extend = complain
  206. insert = complain
  207. pop = complain
  208. remove = complain
  209. sort = complain
  210. reverse = complain
  211. class DictWrapper(dict):
  212. """
  213. Wrap accesses to a dictionary so that certain values (those starting with
  214. the specified prefix) are passed through a function before being returned.
  215. The prefix is removed before looking up the real value.
  216. Used by the SQL construction code to ensure that values are correctly
  217. quoted before being used.
  218. """
  219. def __init__(self, data, func, prefix):
  220. super().__init__(data)
  221. self.func = func
  222. self.prefix = prefix
  223. def __getitem__(self, key):
  224. """
  225. Retrieve the real value after stripping the prefix string (if
  226. present). If the prefix is present, pass the value through self.func
  227. before returning, otherwise return the raw value.
  228. """
  229. use_func = key.startswith(self.prefix)
  230. if use_func:
  231. key = key[len(self.prefix):]
  232. value = super().__getitem__(key)
  233. if use_func:
  234. return self.func(value)
  235. return value
  236. def _destruct_iterable_mapping_values(data):
  237. for i, elem in enumerate(data):
  238. if len(elem) != 2:
  239. raise ValueError(
  240. 'dictionary update sequence element #{} has '
  241. 'length {}; 2 is required.'.format(i, len(elem))
  242. )
  243. if not isinstance(elem[0], str):
  244. raise ValueError('Element key %r invalid, only strings are allowed' % elem[0])
  245. yield tuple(elem)
  246. class CaseInsensitiveMapping(Mapping):
  247. """
  248. Mapping allowing case-insensitive key lookups. Original case of keys is
  249. preserved for iteration and string representation.
  250. Example::
  251. >>> ci_map = CaseInsensitiveMapping({'name': 'Jane'})
  252. >>> ci_map['Name']
  253. Jane
  254. >>> ci_map['NAME']
  255. Jane
  256. >>> ci_map['name']
  257. Jane
  258. >>> ci_map # original case preserved
  259. {'name': 'Jane'}
  260. """
  261. def __init__(self, data):
  262. if not isinstance(data, Mapping):
  263. data = {k: v for k, v in _destruct_iterable_mapping_values(data)}
  264. self._store = {k.lower(): (k, v) for k, v in data.items()}
  265. def __getitem__(self, key):
  266. return self._store[key.lower()][1]
  267. def __len__(self):
  268. return len(self._store)
  269. def __eq__(self, other):
  270. return isinstance(other, Mapping) and {
  271. k.lower(): v for k, v in self.items()
  272. } == {
  273. k.lower(): v for k, v in other.items()
  274. }
  275. def __iter__(self):
  276. return (original_key for original_key, value in self._store.values())
  277. def __repr__(self):
  278. return repr({key: value for key, value in self._store.values()})
  279. def copy(self):
  280. return self