Debian Codegraph @

src/anyio/functools.py

raw
1 from __future__ import annotations
2
3 __all__ = (
4 "AsyncCacheInfo",
5 "AsyncCacheParameters",
6 "AsyncLRUCacheWrapper",
7 "cache",
8 "lru_cache",
9 "reduce",
10 )
11
12 import functools
13 import sys
14 from collections import OrderedDict
15 from collections.abc import (
16 AsyncIterable,
17 Awaitable,
18 Callable,
19 Coroutine,
20 Hashable,
21 Iterable,
22 )
23 from functools import update_wrapper
24 from inspect import iscoroutinefunction
25 from typing import (
26 Any,
27 Generic,
28 NamedTuple,
29 TypedDict,
30 TypeVar,
31 cast,
32 final,
33 overload,
34 )
35 from weakref import WeakKeyDictionary
36
37 from ._core._synchronization import Lock
38 from .lowlevel import RunVar, checkpoint
39
40 if sys.version_info >= (3, 11):
41 from typing import ParamSpec
42 else:
43 from typing_extensions import ParamSpec
44
45 T = TypeVar("T")
46 S = TypeVar("S")
47 P = ParamSpec("P")
48 lru_cache_items: RunVar[
49 WeakKeyDictionary[
50 AsyncLRUCacheWrapper[Any, Any],
51 OrderedDict[Hashable, tuple[_InitialMissingType, Lock] | tuple[Any, None]],
52 ]
53 ] = RunVar("lru_cache_items")
54
55
56 class _InitialMissingType:
57 pass
58
59
60 initial_missing: _InitialMissingType = _InitialMissingType()
61
62
63 class AsyncCacheInfo(NamedTuple):
64 hits: int
65 misses: int
66 maxsize: int | None
67 currsize: int
68
69
70 class AsyncCacheParameters(TypedDict):
71 maxsize: int | None
72 typed: bool
73 always_checkpoint: bool
74
75
76 class _LRUMethodWrapper(Generic[T]):
77 def __init__(self, wrapper: AsyncLRUCacheWrapper[..., T], instance: object):
78 self.__wrapper = wrapper
79 self.__instance = instance
80
81 def cache_info(self) -> AsyncCacheInfo:
82 return self.__wrapper.cache_info()
83
84 def cache_parameters(self) -> AsyncCacheParameters:
85 return self.__wrapper.cache_parameters()
86
87 def cache_clear(self) -> None:
88 self.__wrapper.cache_clear()
89
90 async def __call__(self, *args: Any, **kwargs: Any) -> T:
91 if self.__instance is None:
92 return await self.__wrapper(*args, **kwargs)
93
94 return await self.__wrapper(self.__instance, *args, **kwargs)
95
96
97 @final
98 class AsyncLRUCacheWrapper(Generic[P, T]):
99 def __init__(
100 self,
101 func: Callable[P, Awaitable[T]],
102 maxsize: int | None,
103 typed: bool,
104 always_checkpoint: bool,
105 ):
106 self.__wrapped__ = func
107 self._hits: int = 0
108 self._misses: int = 0
109 self._maxsize = max(maxsize, 0) if maxsize is not None else None
110 self._currsize: int = 0
111 self._typed = typed
112 self._always_checkpoint = always_checkpoint
113 update_wrapper(self, func)
114
115 def cache_info(self) -> AsyncCacheInfo:
116 return AsyncCacheInfo(self._hits, self._misses, self._maxsize, self._currsize)
117
118 def cache_parameters(self) -> AsyncCacheParameters:
119 return {
120 "maxsize": self._maxsize,
121 "typed": self._typed,
122 "always_checkpoint": self._always_checkpoint,
123 }
124
125 def cache_clear(self) -> None:
126 if cache := lru_cache_items.get(None):
127 cache.pop(self, None)
128 self._hits = self._misses = self._currsize = 0
129
130 async def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T:
131 # Easy case first: if maxsize == 0, no caching is done
132 if self._maxsize == 0:
133 value = await self.__wrapped__(*args, **kwargs)
134 self._misses += 1
135 return value
136
137 # The key is constructed as a flat tuple to avoid memory overhead
138 key: tuple[Any, ...] = args
139 if kwargs:
140 # initial_missing is used as a separator
141 key += (initial_missing,) + sum(kwargs.items(), ())
142
143 if self._typed:
144 key += tuple(type(arg) for arg in args)
145 if kwargs:
146 key += (initial_missing,) + tuple(type(val) for val in kwargs.values())
147
148 try:
149 cache = lru_cache_items.get()
150 except LookupError:
151 cache = WeakKeyDictionary()
152 lru_cache_items.set(cache)
153
154 try:
155 cache_entry = cache[self]
156 except KeyError:
157 cache_entry = cache[self] = OrderedDict()
158
159 cached_value: T | _InitialMissingType
160 try:
161 cached_value, lock = cache_entry[key]
162 except KeyError:
163 # We're the first task to call this function
164 cached_value, lock = (
165 initial_missing,
166 Lock(fast_acquire=not self._always_checkpoint),
167 )
168 cache_entry[key] = cached_value, lock
169
170 if lock is None:
171 # The value was already cached
172 self._hits += 1
173 cache_entry.move_to_end(key)
174 if self._always_checkpoint:
175 await checkpoint()
176
177 return cast(T, cached_value)
178
179 async with lock:
180 # Check if another task filled the cache while we acquired the lock
181 if (cached_value := cache_entry[key][0]) is initial_missing:
182 self._misses += 1
183 if self._maxsize is not None and self._currsize >= self._maxsize:
184 cache_entry.popitem(last=False)
185 else:
186 self._currsize += 1
187
188 value = await self.__wrapped__(*args, **kwargs)
189 cache_entry[key] = value, None
190 else:
191 # Another task filled the cache while we were waiting for the lock
192 self._hits += 1
193 cache_entry.move_to_end(key)
194 value = cast(T, cached_value)
195
196 return value
197
198 def __get__(
199 self, instance: object, owner: type | None = None
200 ) -> _LRUMethodWrapper[T]:
201 wrapper = _LRUMethodWrapper(self, instance)
202 update_wrapper(wrapper, self.__wrapped__)
203 return wrapper
204
205
206 class _LRUCacheWrapper(Generic[T]):
207 def __init__(self, maxsize: int | None, typed: bool, always_checkpoint: bool):
208 self._maxsize = maxsize
209 self._typed = typed
210 self._always_checkpoint = always_checkpoint
211
212 @overload
213 def __call__( # type: ignore[overload-overlap]
214 self, func: Callable[P, Coroutine[Any, Any, T]], /
215 ) -> AsyncLRUCacheWrapper[P, T]: ...
216
217 @overload
218 def __call__(
219 self, func: Callable[..., T], /
220 ) -> functools._lru_cache_wrapper[T]: ...
221
222 def __call__(
223 self, f: Callable[P, Coroutine[Any, Any, T]] | Callable[..., T], /
224 ) -> AsyncLRUCacheWrapper[P, T] | functools._lru_cache_wrapper[T]:
225 if iscoroutinefunction(f):
226 return AsyncLRUCacheWrapper(
227 f, self._maxsize, self._typed, self._always_checkpoint
228 )
229
230 return functools.lru_cache(maxsize=self._maxsize, typed=self._typed)(f) # type: ignore[arg-type]
231
232
233 @overload
234 def cache( # type: ignore[overload-overlap]
235 func: Callable[P, Coroutine[Any, Any, T]], /
236 ) -> AsyncLRUCacheWrapper[P, T]: ...
237
238
239 @overload
240 def cache(func: Callable[..., T], /) -> functools._lru_cache_wrapper[T]: ...
241
242
243 def cache(
244 func: Callable[..., T] | Callable[P, Coroutine[Any, Any, T]], /
245 ) -> AsyncLRUCacheWrapper[P, T] | functools._lru_cache_wrapper[T]:
246 """
247 A convenient shortcut for :func:`lru_cache` with ``maxsize=None``.
248
249 This is the asynchronous equivalent to :func:`functools.cache`.
250
251 """
252 return lru_cache(maxsize=None)(func)
253
254
255 @overload
256 def lru_cache(
257 *, maxsize: int | None = ..., typed: bool = ..., always_checkpoint: bool = ...
258 ) -> _LRUCacheWrapper[Any]: ...
259
260
261 @overload
262 def lru_cache( # type: ignore[overload-overlap]
263 func: Callable[P, Coroutine[Any, Any, T]], /
264 ) -> AsyncLRUCacheWrapper[P, T]: ...
265
266
267 @overload
268 def lru_cache(func: Callable[..., T], /) -> functools._lru_cache_wrapper[T]: ...
269
270
271 def lru_cache(
272 func: Callable[P, Coroutine[Any, Any, T]] | Callable[..., T] | None = None,
273 /,
274 *,
275 maxsize: int | None = 128,
276 typed: bool = False,
277 always_checkpoint: bool = False,
278 ) -> (
279 AsyncLRUCacheWrapper[P, T] | functools._lru_cache_wrapper[T] | _LRUCacheWrapper[Any]
280 ):
281 """
282 An asynchronous version of :func:`functools.lru_cache`.
283
284 If a synchronous function is passed, the standard library
285 :func:`functools.lru_cache` is applied instead.
286
287 :param always_checkpoint: if ``True``, every call to the cached function will be
288 guaranteed to yield control to the event loop at least once
289
290 .. note:: Caches and locks are managed on a per-event loop basis.
291
292 """
293 if func is None:
294 return _LRUCacheWrapper[Any](maxsize, typed, always_checkpoint)
295
296 if not callable(func):
297 raise TypeError("the first argument must be callable")
298
299 return _LRUCacheWrapper[T](maxsize, typed, always_checkpoint)(func)
300
301
302 @overload
303 async def reduce(
304 function: Callable[[T, S], Awaitable[T]],
305 iterable: Iterable[S] | AsyncIterable[S],
306 /,
307 initial: T,
308 ) -> T: ...
309
310
311 @overload
312 async def reduce(
313 function: Callable[[T, T], Awaitable[T]],
314 iterable: Iterable[T] | AsyncIterable[T],
315 /,
316 ) -> T: ...
317
318
319 async def reduce( # type: ignore[misc]
320 function: Callable[[T, T], Awaitable[T]] | Callable[[T, S], Awaitable[T]],
321 iterable: Iterable[T] | Iterable[S] | AsyncIterable[T] | AsyncIterable[S],
322 /,
323 initial: T | _InitialMissingType = initial_missing,
324 ) -> T:
325 """
326 Asynchronous version of :func:`functools.reduce`.
327
328 :param function: a coroutine function that takes two arguments: the accumulated
329 value and the next element from the iterable
330 :param iterable: an iterable or async iterable
331 :param initial: the initial value (if missing, the first element of the iterable is
332 used as the initial value)
333
334 """
335 element: Any
336 function_called = False
337 if isinstance(iterable, AsyncIterable):
338 async_it = iterable.__aiter__()
339 if initial is initial_missing:
340 try:
341 value = cast(T, await async_it.__anext__())
342 except StopAsyncIteration:
343 raise TypeError(
344 "reduce() of empty sequence with no initial value"
345 ) from None
346 else:
347 value = cast(T, initial)
348
349 async for element in async_it:
350 value = await function(value, element)
351 function_called = True
352 elif isinstance(iterable, Iterable):
353 it = iter(iterable)
354 if initial is initial_missing:
355 try:
356 value = cast(T, next(it))
357 except StopIteration:
358 raise TypeError(
359 "reduce() of empty sequence with no initial value"
360 ) from None
361 else:
362 value = cast(T, initial)
363
364 for element in it:
365 value = await function(value, element)
366 function_called = True
367 else:
368 raise TypeError("reduce() argument 2 must be an iterable or async iterable")
369
370 # Make sure there is at least one checkpoint, even if an empty iterable and an
371 # initial value were given
372 if not function_called:
373 await checkpoint()
374
375 return value