|
| 1 | +import typing |
| 2 | + |
| 3 | +T = typing.TypeVar("T") |
| 4 | +DependableFunc = typing.Union[ |
| 5 | + typing.Callable[..., typing.Awaitable[T]], |
| 6 | + typing.Callable[..., typing.AsyncContextManager[T]], |
| 7 | +] |
| 8 | +F = typing.TypeVar("F", bound=DependableFunc) |
| 9 | + |
| 10 | + |
| 11 | +class Dependable(typing.Generic[T]): |
| 12 | + __slots__ = ("func", "cached") |
| 13 | + |
| 14 | + def __init__(self, func: DependableFunc[T], cached: bool = None) -> None: |
| 15 | + self.func = func |
| 16 | + self.cached = cached |
| 17 | + |
| 18 | + def __eq__(self, other: typing.Any) -> bool: |
| 19 | + if not isinstance(other, Dependable): |
| 20 | + return False |
| 21 | + return self.func == other.func and self.cached == other.cached |
| 22 | + |
| 23 | + def __hash__(self) -> int: |
| 24 | + return hash((self.func, self.cached)) |
| 25 | + |
| 26 | + def __repr__(self) -> str: |
| 27 | + attrs = [f"func={self.func!r}"] |
| 28 | + if self.cached: |
| 29 | + attrs.append("cached") |
| 30 | + return f"{self.__class__.__name__}({', '.join(attrs)})" |
| 31 | + |
| 32 | + |
| 33 | +class DependablesCache(typing.Mapping[Dependable, typing.Any]): |
| 34 | + def __init__(self) -> None: |
| 35 | + self._last_id = 0 |
| 36 | + self._cached_dependables: typing.Dict[Dependable, typing.Any] = {} |
| 37 | + self._cachable_funcs: typing.Set[DependableFunc] = set() |
| 38 | + |
| 39 | + def __getitem__(self, dep: Dependable[T]) -> T: |
| 40 | + return self._cached_dependables[dep] |
| 41 | + |
| 42 | + def __setitem__(self, dep: Dependable[T], value: T) -> None: |
| 43 | + self._cached_dependables[dep] = value |
| 44 | + |
| 45 | + def __len__(self) -> int: |
| 46 | + return len(self._cached_dependables) |
| 47 | + |
| 48 | + def __iter__(self) -> typing.Iterator[Dependable]: |
| 49 | + return iter(self._cached_dependables) |
| 50 | + |
| 51 | + def should_cache(self, dep: Dependable[T]) -> bool: |
| 52 | + if dep.cached: |
| 53 | + return dep not in self |
| 54 | + if dep.cached is None: |
| 55 | + # 'cached=...' was not passed to 'depends()'. |
| 56 | + # => Should cache if the dependable function was decorated with '@cached' |
| 57 | + return dep.func in self._cachable_funcs |
| 58 | + return False |
| 59 | + |
| 60 | + def cached(self, func: F) -> F: |
| 61 | + self._cachable_funcs.add(func) |
| 62 | + return func |
| 63 | + |
| 64 | + def clear(self) -> None: |
| 65 | + self._cached_dependables = {} |
| 66 | + self._cachable_funcs = set() |
| 67 | + |
| 68 | + |
| 69 | +cache = DependablesCache() |
0 commit comments