Skip to content

Instantly share code, notes, and snippets.

@lachesis
Last active December 3, 2022 20:25
Show Gist options
  • Save lachesis/dfc22ac7c55d0eac99532d080c4a7f4c to your computer and use it in GitHub Desktop.
Save lachesis/dfc22ac7c55d0eac99532d080c4a7f4c to your computer and use it in GitHub Desktop.
Python expiring LRU
# License: Public Domain, use as you like, no warranty
import time
import threading
import pylru # from pip
class ExpiringLRUCache(object):
def __init__(self, size, exp=7200):
self.exp = exp
self.size = size
self.lru = pylru.lrucache(size)
self.lock = threading.Lock()
def clear(self, key):
with self.lock:
try:
del self.lru[key]
except KeyError:
pass
def set(self, key, val, exp=None):
kv = (time.time() + (exp or self.exp), val)
with self.lock:
self.lru[key] = kv
def get(self, key):
with self.lock:
x = self.lru.get(key)
if x is None:
return None
expts, val = x
if expts < time.time():
with self.lock:
try:
del self.lru[key]
except Exception:
pass
return None
return val
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment