Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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 10KB

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