Search code examples
pythonlambdasympy

Save/load sympy lambdifed expressions


Imagine the following three step process:

  • I use sympy to build a large and somewhat complicated expression (this process costs a lot of time).
  • That expression is then converted into a lambda function using sympy.lambdify (also slow).
  • Said function is then evaluated (fast)

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.


Solution

  • 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"))