Skip to content

Instantly share code, notes, and snippets.

@sanketsudake
Created February 5, 2017 16:02
Show Gist options
  • Save sanketsudake/613a3ab92d7de8aac602fe2f1f29a341 to your computer and use it in GitHub Desktop.
Save sanketsudake/613a3ab92d7de8aac602fe2f1f29a341 to your computer and use it in GitHub Desktop.
Python caching function result
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