Created
January 6, 2020 14:02
-
-
Save rossant/1ce41be73d149757766a1e3dffc8c964 to your computer and use it in GitHub Desktop.
Custom LRU cache implementation that gives access to the underlying cache dictionary.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def lru_cache(maxsize=0): | |
"""Custom LRU cache implementation that gives access to the underlying cache dictionary. [better to used functools one if you don't need this]""" | |
def wrap(f): | |
cache = {} | |
last_used = [] | |
def wrapped(*args): | |
if args in cache: | |
# HIT. | |
# Update the last_used list. | |
if last_used[0] != args: | |
i = last_used.index(args) | |
last_used.insert(0, last_used.pop(i)) | |
assert set(cache) == set(last_used) | |
return cache[args] | |
# MISS. | |
out = f(*args) | |
cache[args] = out | |
last_used.insert(0, args) | |
if maxsize > 0 and len(cache) > maxsize: | |
cache.pop(last_used[-1], None) | |
del last_used[-1] | |
assert set(cache) == set(last_used) | |
return out | |
wrapped._cache = cache | |
wrapped._last_used = last_used | |
return wrapped | |
return wrap | |
def test_lru_cache(): | |
_calls = [] | |
def f(x): | |
_calls.append(x) | |
return x * x | |
fc = lru_cache(maxsize=3)(f) | |
assert fc(2) == 4 | |
assert len(_calls) == 1 | |
assert fc._cache == {(2,): 4} | |
assert fc._last_used == [(2,)] | |
assert fc(2) == 4 | |
assert len(_calls) == 1 | |
assert fc(3) == 9 | |
assert len(_calls) == 2 | |
assert fc._cache == {(2,): 4, (3,): 9} | |
assert fc._last_used == [(3,), (2,)] | |
assert fc(4) == 16 | |
assert len(_calls) == 3 | |
assert fc._cache == {(2,): 4, (3,): 9, (4,): 16} | |
assert fc._last_used == [(4,), (3,), (2,)] | |
assert fc(5) == 25 | |
assert len(_calls) == 4 | |
assert fc._cache == {(3,): 9, (4,): 16, (5,): 25} | |
assert fc._last_used == [(5,), (4,), (3,)] | |
assert fc(3) == 9 | |
assert len(_calls) == 4 | |
assert fc._cache == {(3,): 9, (4,): 16, (5,): 25} | |
assert fc._last_used == [(3,), (5,), (4,)] | |
assert fc(2) == 4 | |
assert len(_calls) == 5 | |
assert fc._cache == {(3,): 9, (5,): 25, (2,): 4} | |
assert fc._last_used == [(2,), (3,), (5,)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment