Skip to content

Instantly share code, notes, and snippets.

@earonesty
Created March 21, 2022 21:55
Show Gist options
  • Save earonesty/c1cd4c634cfc1f9e3f34d0b4b056651c to your computer and use it in GitHub Desktop.
Save earonesty/c1cd4c634cfc1f9e3f34d0b4b056651c to your computer and use it in GitHub Desktop.
extremely simple lru set in python
class LRUSet(set):
def __init__(self, *args, max_size=None, **kws):
self.max_size = max_size
super().__init__(*args, **kws)
def add(self, ent):
if len(self) >= self.max_size:
self.pop()
super().discard(ent)
super().add(ent)
def test_lruset():
s = LRUSet([1,2,3,4,5,6], max_size=6)
s.add(7)
assert s == {2,3,4,5,6,7}
s.remove(3)
s.add(8)
s.add(9)
assert s == {4,5,6,7,8,9}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment