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

Method decorator

other/lfu_cache.py:281–313  ·  view source on GitHub ↗

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

(
        cls: type[LFUCache[T, U]], size: int = 128
    )

Source from the content-addressed store, hash-verified

279
280 @classmethod
281 def decorator(
282 cls: type[LFUCache[T, U]], size: int = 128
283 ) -> Callable[[Callable[[T], U]], Callable[..., U]]:
284 """
285 Decorator version of LFU Cache
286
287 Decorated function must be function of T -> U
288 """
289
290 def cache_decorator_inner(func: Callable[[T], U]) -> Callable[..., U]:
291 # variable to map the decorator functions to their respective instance
292 decorator_function_to_instance_map: dict[
293 Callable[[T], U], LFUCache[T, U]
294 ] = {}
295
296 def cache_decorator_wrapper(*args: T) -> U:
297 if func not in decorator_function_to_instance_map:
298 decorator_function_to_instance_map[func] = LFUCache(size)
299
300 result = decorator_function_to_instance_map[func].get(args[0])
301 if result is None:
302 result = func(*args)
303 decorator_function_to_instance_map[func].put(args[0], result)
304 return result
305
306 def cache_info() -> LFUCache[T, U]:
307 return decorator_function_to_instance_map[func]
308
309 setattr(cache_decorator_wrapper, "cache_info", cache_info) # noqa: B010
310
311 return cache_decorator_wrapper
312
313 return cache_decorator_inner
314
315
316if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected