55# ----------------------------------------------------------------------------------------
66from datetime import datetime , timedelta , timezone
77from functools import lru_cache , wraps
8+ from typing import Any , Callable , TypeVar , cast
89
910from backpack .logger import get_logger
1011
1112log = get_logger ('Python Backpack - Cache' )
1213
14+ F = TypeVar ('F' , bound = Callable [..., Any ])
1315
14- def timed_lru_cache (seconds : int , maxsize : int = 128 ):
16+
17+ def timed_lru_cache (seconds : int , maxsize : int = 128 ) -> Callable [[F ], F ]:
1518 """Lru_cache with expiration time.
1619
1720 Args:
@@ -36,10 +39,10 @@ def my_function():
3639
3740 """
3841
39- def wrapper_cache (func ) :
40- func = lru_cache (maxsize = maxsize )(func )
41- func .lifetime = timedelta (seconds = seconds )
42- func .expiration = datetime .now (timezone .utc ) + func .lifetime
42+ def wrapper_cache (func : F ) -> F :
43+ cached_func = cast ( Any , lru_cache (maxsize = maxsize )(func ) )
44+ cached_func .lifetime = timedelta (seconds = seconds )
45+ cached_func .expiration = datetime .now (timezone .utc ) + cached_func .lifetime
4346
4447 @wraps (func )
4548 def wrapped_func (* args , force_clear : bool = False , show_log : bool = False , ** kwargs ):
@@ -54,15 +57,15 @@ def wrapped_func(*args, force_clear: bool = False, show_log: bool = False, **kwa
5457 function result
5558 """
5659
57- if force_clear or datetime .now (timezone .utc ) >= func .expiration :
60+ if force_clear or datetime .now (timezone .utc ) >= cached_func .expiration :
5861 if show_log :
59- log .debug (f'Cache cleared for { func .__name__ } ' )
62+ log .debug (f'Cache cleared for { cached_func .__name__ } ' )
6063
61- func .cache_clear ()
62- func .expiration = datetime .now (timezone .utc ) + func .lifetime
64+ cached_func .cache_clear ()
65+ cached_func .expiration = datetime .now (timezone .utc ) + cached_func .lifetime
6366
64- return func (* args , ** kwargs )
67+ return cached_func (* args , ** kwargs )
6568
66- return wrapped_func
69+ return cast ( F , wrapped_func )
6770
6871 return wrapper_cache
0 commit comments