I want to save/serialize a Sympy-Lambdify func into a file and use/load it by another python-program later.
Case 1: it works well
import dill
import sympy as sp
from sympy.utilities.lambdify import lambdify
dill.settings['recurse'] = True
a,b = sp.symbols('a, b')
expr = a**2 + 2*a + 1 + b
func = lambdify((a,b), expr)
myfunc = dill.loads(dill.dumps(func))
print(myfunc)
print(type(myfunc))
print(myfunc(2,3))
output:
<function <lambda> at 0x00000210AA0D6598>
<class 'function'>
12
Case 2: return errors
import dill
import sympy as sp
from sympy.utilities.lambdify import lambdify
dill.settings['recurse'] = True
a,b = sp.symbols('a, b')
expr = a**2 + 2*a + 1 + b
func = lambdify((a,b), expr)
with open('expr', 'wb') as outf:
dill.dump(expr, outf)
with open('expr','rb') as inf:
myfunc= dill.load(inf)
print(myfunc)
print(type(myfunc))
print(myfunc(2,3))
Output:
a**2 + 2*a + b + 1
<class 'sympy.core.add.Add'>
Traceback (most recent call last):
File "test.py", line 25, in <module>
print(myfunc(2,3))
TypeError: 'Add' object is not callable
Could someone help me to fix it?
Thank you all in advance!
instead of expr
put func
in dill.dump()
:
with open('expr', 'wb') as outf:
dill.dump(func, outf)
Output
<function <lambda> at 0x7fd3015c4510>
<class 'function'>
12