Last active
July 26, 2019 14:27
-
-
Save saintsGrad15/500b868e0a617b1b15d6 to your computer and use it in GitHub Desktop.
A memoize wrapper for use as a decorator
This file contains 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
# Author : John Carrell | |
# | |
# A memoize function to use as a decorator | |
# | |
# Memoization is caching the arguments to and result of a function. | |
# Then, the next time that function is called with the same arguments the result is taken from the cache rather invoking the function. | |
# Memoization is effective when executing the logic of a particularly function is expensive. | |
# For instance, expensive calculations, network I/O or file access would be effective things to avoid if the yielded value won't or doesn't need to change. | |
# | |
# A detministic function is one where for a given input the same output is always produced. | |
def memoize(func): | |
cache = {} | |
def call_func(*args, **kwargs): | |
if (args, repr(kwargs)) in cache: | |
return cache[(args, repr(kwargs))] | |
else: | |
result = func(*args, **kwargs) | |
cache[(args, repr(kwargs))] = result | |
return result | |
return call_func |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment