Skip to content

Instantly share code, notes, and snippets.

@acenturyandabit
Last active February 3, 2024 00:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acenturyandabit/16251fce69c319d6b58884fef878dd04 to your computer and use it in GitHub Desktop.
Save acenturyandabit/16251fce69c319d6b58884fef878dd04 to your computer and use it in GitHub Desktop.
ipynb cache
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