Imagine the following three step process:
sympy.lambdify
(also slow). Ideally, steps 1 and 2 are only done once, while step 3 will be evaluated multiple times. Unfortunately the evaluations of step 3 are spread out over time (and different python sessions!)
I'm searching for a way to save the "lambdified" expression to disk, so that I can load and use them at a later point. Unfortunately pickle does not support lambda functions. Also my lambda function uses numpy.
I could of course create a matching function by hand and use that, but that seems inefficient and error-prone.
you can use "dill", as described here
How to serialize sympy lambdified function?
and
How to use dill to serialize a class definition?
You have to import dill and set the variable 'recursive' to the value "True".
import dill
dill.settings['recurse'] = True
Lets say f is your lambdified function. You can dump it to disk using the following.
dill.dump(f, open("myfile", "wb"))
Afterwards you can load the function with the following line. This can be also done from another python script.
f_new=dill.load(open("myfile", "rb"))
The above works well. In my case with Python 3.6, I needed to explicitly indicate that the saved and loaded files were binary. So modified the code above to:
dill.dump(f, open("myfile", "wb"))
and for reading:
f_new=dill.load(open("myfile", "rb"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With