python 3: dump/load sympy lambdify-expression 时出错

python 3: error when dump/load sympy lambdify-epression

我想 save/serialize 一个 Sympy-Lambdify 函数到一个文件中,然后 use/load 由另一个 python 程序稍后。

案例一:效果很好

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: return错误

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

有人可以帮我解决吗?

提前谢谢大家!

而不是 exprfunc 放入 dill.dump():

with open('expr', 'wb') as outf:
    dill.dump(func, outf)

输出

<function <lambda> at 0x7fd3015c4510>
<class 'function'>
12