Development of an internal social media platform with personalised dashboards for students
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 13KB

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