Created
October 31, 2021 16:35
-
-
Save nixbytes/bfd7e80fbaf880d2c16742c30fa6f02b to your computer and use it in GitHub Desktop.
Memoization, or caching, is an incredibly important feature of any highly-performant system.
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
| '''' | |
| When the function is called, we'll create a hashable key from the supplied arguments by freezing | |
| the positional arguments and the keyword arguments, hoping that the arguments themselves are hashable. | |
| If we haven't seen these arguments before, we'll compute the result and store it in the cache. Then, we'll | |
| return the result from the cache. This way, if the function is called multiple times with the same arguments, | |
| each invocation after the first will only use the value from cache, and won't recompute the function. | |
| ''' | |
| import functools | |
| def memoize(function): | |
| function._cache = {} | |
| @functools.wraps(function) | |
| def wrapper(*args, **kwargs): | |
| key = (args, tuple(kwargs.items())) | |
| if key not in function._cache: | |
| function._cache[key] = function(*args, **kwargs) | |
| return function._cache[key] | |
| return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment