@@ -219,7 +219,7 @@ def wrapper(*args, **kwds):
219219
220220 def wrapper (* args , ** kwds ):
221221 # size limited caching that tracks accesses by recency
222- nonlocal hits , misses
222+ nonlocal root , hits , misses
223223 key = make_key (args , kwds , typed ) if kwds or typed else args
224224 with lock :
225225 link = cache_get (key )
@@ -236,16 +236,21 @@ def wrapper(*args, **kwds):
236236 return result
237237 result = user_function (* args , ** kwds )
238238 with lock :
239- # put result in a new link at the front of the list
240- last = root [PREV ]
241- link = [last , root , key , result ]
242- cache [key ] = last [NEXT ] = root [PREV ] = link
243- if _len (cache ) > maxsize :
244- # purge the least recently used cache entry
245- old_prev , old_next , old_key , old_result = root [NEXT ]
246- root [NEXT ] = old_next
247- old_next [PREV ] = root
248- del cache [old_key ]
239+ if _len (cache ) < maxsize :
240+ # put result in a new link at the front of the list
241+ last = root [PREV ]
242+ link = [last , root , key , result ]
243+ cache [key ] = last [NEXT ] = root [PREV ] = link
244+ else :
245+ # use root to store the new key and result
246+ root [KEY ] = key
247+ root [RESULT ] = result
248+ cache [key ] = root
249+ # empty the oldest link and make it the new root
250+ root = root [NEXT ]
251+ del cache [root [KEY ]]
252+ root [KEY ] = None
253+ root [RESULT ] = None
249254 misses += 1
250255 return result
251256
0 commit comments