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.

functional.py 15KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. import copy
  2. import itertools
  3. import operator
  4. import warnings
  5. from functools import total_ordering, wraps
  6. class cached_property:
  7. """
  8. Decorator that converts a method with a single self argument into a
  9. property cached on the instance.
  10. A cached property can be made out of an existing method:
  11. (e.g. ``url = cached_property(get_absolute_url)``).
  12. """
  13. name = None
  14. @staticmethod
  15. def func(instance):
  16. raise TypeError(
  17. "Cannot use cached_property instance without calling "
  18. "__set_name__() on it."
  19. )
  20. def __init__(self, func, name=None):
  21. from django.utils.deprecation import RemovedInDjango50Warning
  22. if name is not None:
  23. warnings.warn(
  24. "The name argument is deprecated as it's unnecessary as of "
  25. "Python 3.6.",
  26. RemovedInDjango50Warning,
  27. stacklevel=2,
  28. )
  29. self.real_func = func
  30. self.__doc__ = getattr(func, "__doc__")
  31. def __set_name__(self, owner, name):
  32. if self.name is None:
  33. self.name = name
  34. self.func = self.real_func
  35. elif name != self.name:
  36. raise TypeError(
  37. "Cannot assign the same cached_property to two different names "
  38. "(%r and %r)." % (self.name, name)
  39. )
  40. def __get__(self, instance, cls=None):
  41. """
  42. Call the function and put the return value in instance.__dict__ so that
  43. subsequent attribute access on the instance returns the cached value
  44. instead of calling cached_property.__get__().
  45. """
  46. if instance is None:
  47. return self
  48. res = instance.__dict__[self.name] = self.func(instance)
  49. return res
  50. class classproperty:
  51. """
  52. Decorator that converts a method with a single cls argument into a property
  53. that can be accessed directly from the class.
  54. """
  55. def __init__(self, method=None):
  56. self.fget = method
  57. def __get__(self, instance, cls=None):
  58. return self.fget(cls)
  59. def getter(self, method):
  60. self.fget = method
  61. return self
  62. class Promise:
  63. """
  64. Base class for the proxy class created in the closure of the lazy function.
  65. It's used to recognize promises in code.
  66. """
  67. pass
  68. def lazy(func, *resultclasses):
  69. """
  70. Turn any callable into a lazy evaluated callable. result classes or types
  71. is required -- at least one is needed so that the automatic forcing of
  72. the lazy evaluation code is triggered. Results are not memoized; the
  73. function is evaluated on every access.
  74. """
  75. @total_ordering
  76. class __proxy__(Promise):
  77. """
  78. Encapsulate a function call and act as a proxy for methods that are
  79. called on the result of that function. The function is not evaluated
  80. until one of the methods on the result is called.
  81. """
  82. __prepared = False
  83. def __init__(self, args, kw):
  84. self.__args = args
  85. self.__kw = kw
  86. if not self.__prepared:
  87. self.__prepare_class__()
  88. self.__class__.__prepared = True
  89. def __reduce__(self):
  90. return (
  91. _lazy_proxy_unpickle,
  92. (func, self.__args, self.__kw) + resultclasses,
  93. )
  94. def __repr__(self):
  95. return repr(self.__cast())
  96. @classmethod
  97. def __prepare_class__(cls):
  98. for resultclass in resultclasses:
  99. for type_ in resultclass.mro():
  100. for method_name in type_.__dict__:
  101. # All __promise__ return the same wrapper method, they
  102. # look up the correct implementation when called.
  103. if hasattr(cls, method_name):
  104. continue
  105. meth = cls.__promise__(method_name)
  106. setattr(cls, method_name, meth)
  107. cls._delegate_bytes = bytes in resultclasses
  108. cls._delegate_text = str in resultclasses
  109. if cls._delegate_bytes and cls._delegate_text:
  110. raise ValueError(
  111. "Cannot call lazy() with both bytes and text return types."
  112. )
  113. if cls._delegate_text:
  114. cls.__str__ = cls.__text_cast
  115. elif cls._delegate_bytes:
  116. cls.__bytes__ = cls.__bytes_cast
  117. @classmethod
  118. def __promise__(cls, method_name):
  119. # Builds a wrapper around some magic method
  120. def __wrapper__(self, *args, **kw):
  121. # Automatically triggers the evaluation of a lazy value and
  122. # applies the given magic method of the result type.
  123. res = func(*self.__args, **self.__kw)
  124. return getattr(res, method_name)(*args, **kw)
  125. return __wrapper__
  126. def __text_cast(self):
  127. return func(*self.__args, **self.__kw)
  128. def __bytes_cast(self):
  129. return bytes(func(*self.__args, **self.__kw))
  130. def __bytes_cast_encoded(self):
  131. return func(*self.__args, **self.__kw).encode()
  132. def __cast(self):
  133. if self._delegate_bytes:
  134. return self.__bytes_cast()
  135. elif self._delegate_text:
  136. return self.__text_cast()
  137. else:
  138. return func(*self.__args, **self.__kw)
  139. def __str__(self):
  140. # object defines __str__(), so __prepare_class__() won't overload
  141. # a __str__() method from the proxied class.
  142. return str(self.__cast())
  143. def __eq__(self, other):
  144. if isinstance(other, Promise):
  145. other = other.__cast()
  146. return self.__cast() == other
  147. def __lt__(self, other):
  148. if isinstance(other, Promise):
  149. other = other.__cast()
  150. return self.__cast() < other
  151. def __hash__(self):
  152. return hash(self.__cast())
  153. def __mod__(self, rhs):
  154. if self._delegate_text:
  155. return str(self) % rhs
  156. return self.__cast() % rhs
  157. def __add__(self, other):
  158. return self.__cast() + other
  159. def __radd__(self, other):
  160. return other + self.__cast()
  161. def __deepcopy__(self, memo):
  162. # Instances of this class are effectively immutable. It's just a
  163. # collection of functions. So we don't need to do anything
  164. # complicated for copying.
  165. memo[id(self)] = self
  166. return self
  167. @wraps(func)
  168. def __wrapper__(*args, **kw):
  169. # Creates the proxy object, instead of the actual value.
  170. return __proxy__(args, kw)
  171. return __wrapper__
  172. def _lazy_proxy_unpickle(func, args, kwargs, *resultclasses):
  173. return lazy(func, *resultclasses)(*args, **kwargs)
  174. def lazystr(text):
  175. """
  176. Shortcut for the common case of a lazy callable that returns str.
  177. """
  178. return lazy(str, str)(text)
  179. def keep_lazy(*resultclasses):
  180. """
  181. A decorator that allows a function to be called with one or more lazy
  182. arguments. If none of the args are lazy, the function is evaluated
  183. immediately, otherwise a __proxy__ is returned that will evaluate the
  184. function when needed.
  185. """
  186. if not resultclasses:
  187. raise TypeError("You must pass at least one argument to keep_lazy().")
  188. def decorator(func):
  189. lazy_func = lazy(func, *resultclasses)
  190. @wraps(func)
  191. def wrapper(*args, **kwargs):
  192. if any(
  193. isinstance(arg, Promise)
  194. for arg in itertools.chain(args, kwargs.values())
  195. ):
  196. return lazy_func(*args, **kwargs)
  197. return func(*args, **kwargs)
  198. return wrapper
  199. return decorator
  200. def keep_lazy_text(func):
  201. """
  202. A decorator for functions that accept lazy arguments and return text.
  203. """
  204. return keep_lazy(str)(func)
  205. empty = object()
  206. def new_method_proxy(func):
  207. def inner(self, *args):
  208. if (_wrapped := self._wrapped) is empty:
  209. self._setup()
  210. _wrapped = self._wrapped
  211. return func(_wrapped, *args)
  212. inner._mask_wrapped = False
  213. return inner
  214. class LazyObject:
  215. """
  216. A wrapper for another class that can be used to delay instantiation of the
  217. wrapped class.
  218. By subclassing, you have the opportunity to intercept and alter the
  219. instantiation. If you don't need to do that, use SimpleLazyObject.
  220. """
  221. # Avoid infinite recursion when tracing __init__ (#19456).
  222. _wrapped = None
  223. def __init__(self):
  224. # Note: if a subclass overrides __init__(), it will likely need to
  225. # override __copy__() and __deepcopy__() as well.
  226. self._wrapped = empty
  227. def __getattribute__(self, name):
  228. if name == "_wrapped":
  229. # Avoid recursion when getting wrapped object.
  230. return super().__getattribute__(name)
  231. value = super().__getattribute__(name)
  232. # If attribute is a proxy method, raise an AttributeError to call
  233. # __getattr__() and use the wrapped object method.
  234. if not getattr(value, "_mask_wrapped", True):
  235. raise AttributeError
  236. return value
  237. __getattr__ = new_method_proxy(getattr)
  238. def __setattr__(self, name, value):
  239. if name == "_wrapped":
  240. # Assign to __dict__ to avoid infinite __setattr__ loops.
  241. self.__dict__["_wrapped"] = value
  242. else:
  243. if self._wrapped is empty:
  244. self._setup()
  245. setattr(self._wrapped, name, value)
  246. def __delattr__(self, name):
  247. if name == "_wrapped":
  248. raise TypeError("can't delete _wrapped.")
  249. if self._wrapped is empty:
  250. self._setup()
  251. delattr(self._wrapped, name)
  252. def _setup(self):
  253. """
  254. Must be implemented by subclasses to initialize the wrapped object.
  255. """
  256. raise NotImplementedError(
  257. "subclasses of LazyObject must provide a _setup() method"
  258. )
  259. # Because we have messed with __class__ below, we confuse pickle as to what
  260. # class we are pickling. We're going to have to initialize the wrapped
  261. # object to successfully pickle it, so we might as well just pickle the
  262. # wrapped object since they're supposed to act the same way.
  263. #
  264. # Unfortunately, if we try to simply act like the wrapped object, the ruse
  265. # will break down when pickle gets our id(). Thus we end up with pickle
  266. # thinking, in effect, that we are a distinct object from the wrapped
  267. # object, but with the same __dict__. This can cause problems (see #25389).
  268. #
  269. # So instead, we define our own __reduce__ method and custom unpickler. We
  270. # pickle the wrapped object as the unpickler's argument, so that pickle
  271. # will pickle it normally, and then the unpickler simply returns its
  272. # argument.
  273. def __reduce__(self):
  274. if self._wrapped is empty:
  275. self._setup()
  276. return (unpickle_lazyobject, (self._wrapped,))
  277. def __copy__(self):
  278. if self._wrapped is empty:
  279. # If uninitialized, copy the wrapper. Use type(self), not
  280. # self.__class__, because the latter is proxied.
  281. return type(self)()
  282. else:
  283. # If initialized, return a copy of the wrapped object.
  284. return copy.copy(self._wrapped)
  285. def __deepcopy__(self, memo):
  286. if self._wrapped is empty:
  287. # We have to use type(self), not self.__class__, because the
  288. # latter is proxied.
  289. result = type(self)()
  290. memo[id(self)] = result
  291. return result
  292. return copy.deepcopy(self._wrapped, memo)
  293. __bytes__ = new_method_proxy(bytes)
  294. __str__ = new_method_proxy(str)
  295. __bool__ = new_method_proxy(bool)
  296. # Introspection support
  297. __dir__ = new_method_proxy(dir)
  298. # Need to pretend to be the wrapped class, for the sake of objects that
  299. # care about this (especially in equality tests)
  300. __class__ = property(new_method_proxy(operator.attrgetter("__class__")))
  301. __eq__ = new_method_proxy(operator.eq)
  302. __lt__ = new_method_proxy(operator.lt)
  303. __gt__ = new_method_proxy(operator.gt)
  304. __ne__ = new_method_proxy(operator.ne)
  305. __hash__ = new_method_proxy(hash)
  306. # List/Tuple/Dictionary methods support
  307. __getitem__ = new_method_proxy(operator.getitem)
  308. __setitem__ = new_method_proxy(operator.setitem)
  309. __delitem__ = new_method_proxy(operator.delitem)
  310. __iter__ = new_method_proxy(iter)
  311. __len__ = new_method_proxy(len)
  312. __contains__ = new_method_proxy(operator.contains)
  313. def unpickle_lazyobject(wrapped):
  314. """
  315. Used to unpickle lazy objects. Just return its argument, which will be the
  316. wrapped object.
  317. """
  318. return wrapped
  319. class SimpleLazyObject(LazyObject):
  320. """
  321. A lazy object initialized from any function.
  322. Designed for compound objects of unknown type. For builtins or objects of
  323. known type, use django.utils.functional.lazy.
  324. """
  325. def __init__(self, func):
  326. """
  327. Pass in a callable that returns the object to be wrapped.
  328. If copies are made of the resulting SimpleLazyObject, which can happen
  329. in various circumstances within Django, then you must ensure that the
  330. callable can be safely run more than once and will return the same
  331. value.
  332. """
  333. self.__dict__["_setupfunc"] = func
  334. super().__init__()
  335. def _setup(self):
  336. self._wrapped = self._setupfunc()
  337. # Return a meaningful representation of the lazy object for debugging
  338. # without evaluating the wrapped object.
  339. def __repr__(self):
  340. if self._wrapped is empty:
  341. repr_attr = self._setupfunc
  342. else:
  343. repr_attr = self._wrapped
  344. return "<%s: %r>" % (type(self).__name__, repr_attr)
  345. def __copy__(self):
  346. if self._wrapped is empty:
  347. # If uninitialized, copy the wrapper. Use SimpleLazyObject, not
  348. # self.__class__, because the latter is proxied.
  349. return SimpleLazyObject(self._setupfunc)
  350. else:
  351. # If initialized, return a copy of the wrapped object.
  352. return copy.copy(self._wrapped)
  353. def __deepcopy__(self, memo):
  354. if self._wrapped is empty:
  355. # We have to use SimpleLazyObject, not self.__class__, because the
  356. # latter is proxied.
  357. result = SimpleLazyObject(self._setupfunc)
  358. memo[id(self)] = result
  359. return result
  360. return copy.deepcopy(self._wrapped, memo)
  361. __add__ = new_method_proxy(operator.add)
  362. @new_method_proxy
  363. def __radd__(self, other):
  364. return other + self
  365. def partition(predicate, values):
  366. """
  367. Split the values into two sets, based on the return value of the function
  368. (True/False). e.g.:
  369. >>> partition(lambda x: x > 3, range(5))
  370. [0, 1, 2, 3], [4]
  371. """
  372. results = ([], [])
  373. for item in values:
  374. results[predicate(item)].append(item)
  375. return results