I am trying to dump functions into a file, so that I can use this file/function elsewhere. I choose dill
rather than pickle
, because I need dependencies. However, dill
doesn't work if the function has imports inside. For example:
def func():
import numpy
import dill
dill.settings['recurse'] = True
with open("test.pickle","wb") as f:
dill.dump(func,f)
When I restart and load the function back, I get this error,
import dill
func = dill.load(open("test.pickle"))
func()
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input> in <module>()
1 import dill
2 func = dill.load(open("test.pickle"))
----> 3 func()
<ipython-input> in func()
ImportError: __import__ not found
This example works if I use pickle
to dump, but pickle
seems not to save dependencies recursively, so I can't save functions like def fun1(): return fun2()
.
Is there a way to dump functions with both import and dependencies? I feel pickle
or dill
only does half.