@@ -85,7 +85,10 @@ def __getitem__(self, key: K, /) -> V:
8585 def __setitem__ (self , key : K , value : V , / ) -> None :
8686 self ._cache [key ] = value
8787 if len (self ._cache ) > self ._maxsize :
88- self ._cache .pop (next (iter (self ._cache )))
88+ try :
89+ self ._cache .pop (next (iter (self ._cache )))
90+ except (KeyError , StopIteration ):
91+ pass
8992
9093 def setdefault (self , key : K , value : V , / ) -> V :
9194 """Set a value if not already set, returning the actual value.
@@ -103,7 +106,10 @@ def setdefault(self, key: K, value: V, /) -> V:
103106 """
104107 value = self ._cache .setdefault (key , value )
105108 if len (self ._cache ) > self ._maxsize :
106- self ._cache .pop (next (iter (self ._cache )))
109+ try :
110+ self ._cache .pop (next (iter (self ._cache )))
111+ except (KeyError , StopIteration ):
112+ pass
107113 return value
108114
109115 def remove (self , key : K , / ) -> None :
@@ -183,7 +189,11 @@ def _remove_some_expired(self) -> None:
183189 tr = max ((len (self ._expirations ) - self ._maxsize ) >> self ._smooth , 2 )
184190
185191 while self ._expirations and tr > 0 :
186- ts , k = heapq .heappop (self ._expirations )
192+ try :
193+ ts , k = heapq .heappop (self ._expirations )
194+ except IndexError :
195+ continue
196+
187197 if ts < now :
188198 tr -= 1
189199 try :
@@ -211,7 +221,10 @@ def __setitem__(self, key: K, value: V, /) -> None:
211221 self ._cache [key ] = (ts , value )
212222 self ._remove_some_expired ()
213223 if len (self ._cache ) > self ._maxsize :
214- self ._cache .pop (next (iter (self ._cache )))
224+ try :
225+ self ._cache .pop (next (iter (self ._cache )))
226+ except (KeyError , StopIteration ):
227+ pass
215228
216229 def get [T ](self , key : K , default : T , / ) -> V | T :
217230 """Get a value by key or default value.
0 commit comments