Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Commit 3854d0f

Browse files
authored
Add a cached helper to the module API (#14663)
1 parent a4ca770 commit 3854d0f

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

changelog.d/14663.feature

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add a `cached` function to `synapse.module_api` that returns a decorator to cache return values of functions.

synapse/module_api/__init__.py

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
TYPE_CHECKING,
1919
Any,
2020
Callable,
21+
Collection,
2122
Dict,
2223
Generator,
2324
Iterable,
@@ -126,7 +127,7 @@
126127
from synapse.types.state import StateFilter
127128
from synapse.util import Clock
128129
from synapse.util.async_helpers import maybe_awaitable
129-
from synapse.util.caches.descriptors import CachedFunction, cached
130+
from synapse.util.caches.descriptors import CachedFunction, cached as _cached
130131
from synapse.util.frozenutils import freeze
131132

132133
if TYPE_CHECKING:
@@ -136,6 +137,7 @@
136137

137138
T = TypeVar("T")
138139
P = ParamSpec("P")
140+
F = TypeVar("F", bound=Callable[..., Any])
139141

140142
"""
141143
This package defines the 'stable' API which can be used by extension modules which
@@ -185,6 +187,42 @@ class UserIpAndAgent:
185187
last_seen: int
186188

187189

190+
def cached(
191+
*,
192+
max_entries: int = 1000,
193+
num_args: Optional[int] = None,
194+
uncached_args: Optional[Collection[str]] = None,
195+
) -> Callable[[F], CachedFunction[F]]:
196+
"""Returns a decorator that applies a memoizing cache around the function. This
197+
decorator behaves similarly to functools.lru_cache.
198+
199+
Example:
200+
201+
@cached()
202+
def foo('a', 'b'):
203+
...
204+
205+
Added in Synapse v1.74.0.
206+
207+
Args:
208+
max_entries: The maximum number of entries in the cache. If the cache is full
209+
and a new entry is added, the least recently accessed entry will be evicted
210+
from the cache.
211+
num_args: The number of positional arguments (excluding `self`) to use as cache
212+
keys. Defaults to all named args of the function.
213+
uncached_args: A list of argument names to not use as the cache key. (`self` is
214+
always ignored.) Cannot be used with num_args.
215+
216+
Returns:
217+
A decorator that applies a memoizing cache around the function.
218+
"""
219+
return _cached(
220+
max_entries=max_entries,
221+
num_args=num_args,
222+
uncached_args=uncached_args,
223+
)
224+
225+
188226
class ModuleApi:
189227
"""A proxy object that gets passed to various plugin modules so they
190228
can register new users etc if necessary.

0 commit comments

Comments
 (0)