Last active
February 3, 2024 00:11
-
-
Save acenturyandabit/16251fce69c319d6b58884fef878dd04 to your computer and use it in GitHub Desktop.
ipynb cache
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
from typing import Dict, List, Any | |
import inspect | |
Result = Any | |
global_run_cache: Dict[int, Result] = {} | |
def cached_function(fn): | |
def wrapper(*args, **kwargs): | |
global global_run_cache | |
consty_types = [str, int, float] | |
id_of = lambda v: v if type(v) in consty_types else id(v) | |
runHash = hash(tuple([id_of(arg) for arg in args] + [(key, id_of(arg)) for key, arg in kwargs] + [inspect.getsource(fn)])) | |
if runHash not in global_run_cache: | |
global_run_cache[runHash] = fn(*args, **kwargs) | |
return global_run_cache[runHash] | |
return wrapper | |
# Usage: | |
import time | |
@cached_function | |
def some_function(params): | |
time.sleep(params) | |
return params | |
print(some_function(5)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment