Created
February 5, 2017 16:02
-
-
Save sanketsudake/613a3ab92d7de8aac602fe2f1f29a341 to your computer and use it in GitHub Desktop.
Python caching function result
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
from collections import OrderedDict | |
def fifo_cache(max_size=128): | |
def decorator(func): | |
cache = OrderedDict() | |
def _wrapper(*args, **kwargs): | |
key = (tuple(args), tuple(sorted(kwargs.items()))) | |
if key not in cache: | |
if len(cache) == max_size: | |
cache.pop(cache.iterkeys().next()) | |
value = func(*args, **kwargs) | |
cache[key] = value | |
return cache[key] | |
return _wrapper | |
return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment