Last active
November 12, 2017 13:42
-
-
Save poros/1fe7b9ef3e6108216759 to your computer and use it in GitHub Desktop.
Caching with decorators
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
saved = {} | |
def web_lookup(url): | |
if url in saved: | |
return saverd[url] | |
page = urrlib.urlopen(url).read() | |
saved[url] = page | |
return page | |
# NEEDS TO BE A PURE FUNCTION, NO SIDE EFFECTS LIKE PRINT | |
# PYTHON 3 | |
from functools import lru_cache | |
@lru_cache(maxsize=None) | |
def web_lookup(url): | |
return urrlib.urlopen(url).read() | |
# PYTHON 2 | |
@cache | |
def web_lookup(url): | |
return urrlib.urlopen(url).read() | |
from functools import wraps | |
def cache(func): | |
saved = {} | |
@wraps(func) | |
def newfunc(*args): | |
if args in saved: | |
return saved[args] | |
result = func(*args) | |
saved[args] = result | |
return result | |
return newfunc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment