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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. from __future__ import absolute_import
  2. import sys
  3. from collections import Iterable, Mapping
  4. from kombu.five import string_t
  5. __all__ = ['lazy', 'maybe_evaluate', 'is_list', 'maybe_list']
  6. class lazy(object):
  7. """Holds lazy evaluation.
  8. Evaluated when called or if the :meth:`evaluate` method is called.
  9. The function is re-evaluated on every call.
  10. Overloaded operations that will evaluate the promise:
  11. :meth:`__str__`, :meth:`__repr__`, :meth:`__cmp__`.
  12. """
  13. def __init__(self, fun, *args, **kwargs):
  14. self._fun = fun
  15. self._args = args
  16. self._kwargs = kwargs
  17. def __call__(self):
  18. return self.evaluate()
  19. def evaluate(self):
  20. return self._fun(*self._args, **self._kwargs)
  21. def __str__(self):
  22. return str(self())
  23. def __repr__(self):
  24. return repr(self())
  25. def __eq__(self, rhs):
  26. return self() == rhs
  27. def __ne__(self, rhs):
  28. return self() != rhs
  29. def __deepcopy__(self, memo):
  30. memo[id(self)] = self
  31. return self
  32. def __reduce__(self):
  33. return (self.__class__, (self._fun, ), {'_args': self._args,
  34. '_kwargs': self._kwargs})
  35. if sys.version_info[0] < 3:
  36. def __cmp__(self, rhs):
  37. if isinstance(rhs, self.__class__):
  38. return -cmp(rhs, self())
  39. return cmp(self(), rhs)
  40. def maybe_evaluate(value):
  41. """Evaluates if the value is a :class:`lazy` instance."""
  42. if isinstance(value, lazy):
  43. return value.evaluate()
  44. return value
  45. def is_list(l, scalars=(Mapping, string_t), iters=(Iterable, )):
  46. """Return true if the object is iterable (but not
  47. if object is a mapping or string)."""
  48. return isinstance(l, iters) and not isinstance(l, scalars or ())
  49. def maybe_list(l, scalars=(Mapping, string_t)):
  50. """Return list of one element if ``l`` is a scalar."""
  51. return l if l is None or is_list(l, scalars) else [l]
  52. # Compat names (before kombu 3.0)
  53. promise = lazy
  54. maybe_promise = maybe_evaluate