_functools.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. import functools
  2. import types
  3. from typing import Callable, TypeVar
  4. # from jaraco.functools 3.3
  5. def method_cache(method, cache_wrapper=None):
  6. """
  7. Wrap lru_cache to support storing the cache data in the object instances.
  8. Abstracts the common paradigm where the method explicitly saves an
  9. underscore-prefixed protected property on first call and returns that
  10. subsequently.
  11. >>> class MyClass:
  12. ... calls = 0
  13. ...
  14. ... @method_cache
  15. ... def method(self, value):
  16. ... self.calls += 1
  17. ... return value
  18. >>> a = MyClass()
  19. >>> a.method(3)
  20. 3
  21. >>> for x in range(75):
  22. ... res = a.method(x)
  23. >>> a.calls
  24. 75
  25. Note that the apparent behavior will be exactly like that of lru_cache
  26. except that the cache is stored on each instance, so values in one
  27. instance will not flush values from another, and when an instance is
  28. deleted, so are the cached values for that instance.
  29. >>> b = MyClass()
  30. >>> for x in range(35):
  31. ... res = b.method(x)
  32. >>> b.calls
  33. 35
  34. >>> a.method(0)
  35. 0
  36. >>> a.calls
  37. 75
  38. Note that if method had been decorated with ``functools.lru_cache()``,
  39. a.calls would have been 76 (due to the cached value of 0 having been
  40. flushed by the 'b' instance).
  41. Clear the cache with ``.cache_clear()``
  42. >>> a.method.cache_clear()
  43. Same for a method that hasn't yet been called.
  44. >>> c = MyClass()
  45. >>> c.method.cache_clear()
  46. Another cache wrapper may be supplied:
  47. >>> cache = functools.lru_cache(maxsize=2)
  48. >>> MyClass.method2 = method_cache(lambda self: 3, cache_wrapper=cache)
  49. >>> a = MyClass()
  50. >>> a.method2()
  51. 3
  52. Caution - do not subsequently wrap the method with another decorator, such
  53. as ``@property``, which changes the semantics of the function.
  54. See also
  55. http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/
  56. for another implementation and additional justification.
  57. """
  58. cache_wrapper = cache_wrapper or functools.lru_cache()
  59. def wrapper(self, *args, **kwargs):
  60. # it's the first call, replace the method with a cached, bound method
  61. bound_method = types.MethodType(method, self)
  62. cached_method = cache_wrapper(bound_method)
  63. setattr(self, method.__name__, cached_method)
  64. return cached_method(*args, **kwargs)
  65. # Support cache clear even before cache has been created.
  66. wrapper.cache_clear = lambda: None
  67. return wrapper
  68. # From jaraco.functools 3.3
  69. def pass_none(func):
  70. """
  71. Wrap func so it's not called if its first param is None
  72. >>> print_text = pass_none(print)
  73. >>> print_text('text')
  74. text
  75. >>> print_text(None)
  76. """
  77. @functools.wraps(func)
  78. def wrapper(param, *args, **kwargs):
  79. if param is not None:
  80. return func(param, *args, **kwargs)
  81. return wrapper
  82. # From jaraco.functools 4.4
  83. def noop(*args, **kwargs):
  84. """
  85. A no-operation function that does nothing.
  86. >>> noop(1, 2, three=3)
  87. """
  88. _T = TypeVar('_T')
  89. # From jaraco.functools 4.4
  90. def passthrough(func: Callable[..., object]) -> Callable[[_T], _T]:
  91. """
  92. Wrap the function to always return the first parameter.
  93. >>> passthrough(print)('3')
  94. 3
  95. '3'
  96. """
  97. @functools.wraps(func)
  98. def wrapper(first: _T, *args, **kwargs) -> _T:
  99. func(first, *args, **kwargs)
  100. return first
  101. return wrapper # type: ignore[return-value]