I'd like to cache intermediate results. I think that a decorator might help.
I not only want to cache based on function arguments, but also based on the implementation.
Background: I want to cache results between program runs because I am experimenting with the individual implementations, and I want to re-use results of the last run if possible.
It seems to be possible to get a function hash with pickle
:
from hashlib import sha256
import pickle
def foo(bar):
print(bar)
h = sha256()
h.update(pickle.dumps(foo))
The next step would now be to use this in a decorator:
from hashlib import sha256
import pickle
def decorated(f):
def inner(*args, **kwargs):
h = sha256()
h.update(pickle.dumps((args, kwargs, f))
print(h.hexdigest())
return f(*args, **kwargs)
return inner
@decorated
def foo(bar):
print(bar)
foo("bar")
Now pickle
complains:
_pickle.PicklingError: Can't pickle <function foo at 0x7f3d177fdee0>: it's not the same object as __main__.foo
I can understand that my original function got re-assigned during the decoration and that this causes trouble (foo=decorared(foo))
.
Is pickling the correct choice here at all?
edit
This question here shows how to get the source code of a method: How can I get the source code of a Python function? – maybe that's the better approach?