Skip to content

Instantly share code, notes, and snippets.

@justmytwospence
Created July 10, 2014 18:44
Show Gist options
  • Save justmytwospence/625f6b87534fa7eca563 to your computer and use it in GitHub Desktop.
Save justmytwospence/625f6b87534fa7eca563 to your computer and use it in GitHub Desktop.
A decorator that "caches" results of an arbitrary function based on its arguments.
def cache(func):
saved = {}
@wraps(func)
def newfunc(*args):
if args in saved:
return newfunc(*args)
result = func(*args)
saved[args] = result
return result
return newfunc
@justmytwospence
Copy link
Author

Example use:

@cache
def web_lookup(url):
    urllib.urlopen(url).read()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment