11import functools
22import time
33from collections import OrderedDict
4- from typing import (Any , Callable , Generic , Iterable , Iterator , Tuple , TypeVar )
5-
4+ from typing import Any , Callable , Generic , Iterable , Iterator , Tuple , TypeVar
65
76T = TypeVar ("T" )
87
98
109class Cache (Generic [T ]):
1110 """In-memory LRU cache implementation."""
1211
13- def __init__ (
14- self ,
15- max_size : int = 500
16- ):
12+ def __init__ (self , max_size : int = 500 ):
1713 self ._bag : OrderedDict [Any , Any ] = OrderedDict ()
1814 self ._max_size = - 1
1915 self .max_size = max_size
@@ -87,10 +83,7 @@ def clear(self) -> None:
8783class CachedItem (Generic [T ]):
8884 """Container for cached items with update timestamp."""
8985
90- __slots__ = (
91- '_value' ,
92- '_time'
93- )
86+ __slots__ = ("_value" , "_time" )
9487
9588 def __init__ (self , value : T ):
9689 self ._value = value
@@ -114,9 +107,7 @@ class ExpiringCache(Cache[T]):
114107 """A cache whose items can expire by a given function."""
115108
116109 def __init__ (
117- self ,
118- expiration_policy : Callable [[CachedItem [T ]], bool ],
119- max_size : int = 500
110+ self , expiration_policy : Callable [[CachedItem [T ]], bool ], max_size : int = 500
120111 ):
121112 super ().__init__ (max_size )
122113 assert expiration_policy is not None
@@ -157,17 +148,12 @@ def __setitem__(self, key, value: T) -> None:
157148 self ._check_size ()
158149
159150 @classmethod
160- def with_max_age (
161- cls ,
162- max_age : float ,
163- max_size : int = 500
164- ):
151+ def with_max_age (cls , max_age : float , max_size : int = 500 ):
165152 """
166153 Returns an instance of ExpiringCache whose items are invalidated
167154 when they were set more than a given number of seconds ago.
168155 """
169- return cls (lambda item : time .time () - item .time > max_age ,
170- max_size )
156+ return cls (lambda item : time .time () - item .time > max_age , max_size )
171157
172158 def __contains__ (self , key ) -> bool :
173159 if key not in self ._bag :
@@ -188,10 +174,7 @@ def __iter__(self) -> Iterator[Tuple[Any, T]]:
188174 yield (key , item .value )
189175
190176
191- def lazy (
192- max_seconds : int = 1 ,
193- cache = None
194- ):
177+ def lazy (max_seconds : int = 1 , cache = None ):
195178 """
196179 Wraps a function so that it is called up to once
197180 every max_seconds, by input arguments.
@@ -217,6 +200,7 @@ def wrapper(*args):
217200 value = fn (* args )
218201 cache [args ] = (value , now )
219202 return value
203+
220204 return wrapper
221205
222206 return lazy_decorator
0 commit comments