functional.py 13 KB

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