我想将sympy lambdify func保存/序列化到一个文件中,然后由另一个python程序使用/加载它。
案例1
:效果很好
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))
输出:
<function <lambda> at 0x00000210AA0D6598>
<class 'function'>
12
案例2
返回错误
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))
输出:
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
有人能帮我修一下吗?
提前谢谢大家!