MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / decorator

Method decorator

other/lru_cache.py:298–330  ·  view source on GitHub ↗

Decorator version of LRU Cache Decorated function must be function of T -> U

(
        cls, size: int = 128
    )

Source from the content-addressed store, hash-verified

296
297 @classmethod
298 def decorator(
299 cls, size: int = 128
300 ) -> Callable[[Callable[[T], U]], Callable[..., U]]:
301 """
302 Decorator version of LRU Cache
303
304 Decorated function must be function of T -> U
305 """
306
307 def cache_decorator_inner(func: Callable[[T], U]) -> Callable[..., U]:
308 # variable to map the decorator functions to their respective instance
309 decorator_function_to_instance_map: dict[
310 Callable[[T], U], LRUCache[T, U]
311 ] = {}
312
313 def cache_decorator_wrapper(*args: T) -> U:
314 if func not in decorator_function_to_instance_map:
315 decorator_function_to_instance_map[func] = LRUCache(size)
316
317 result = decorator_function_to_instance_map[func].get(args[0])
318 if result is None:
319 result = func(*args)
320 decorator_function_to_instance_map[func].put(args[0], result)
321 return result
322
323 def cache_info() -> LRUCache[T, U]:
324 return decorator_function_to_instance_map[func]
325
326 setattr(cache_decorator_wrapper, "cache_info", cache_info) # noqa: B010
327
328 return cache_decorator_wrapper
329
330 return cache_decorator_inner
331
332
333if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected