首页 > 解决方案 > python 3: error when dump/load sympy lambdify-epression

问题描述

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!

标签: pythonpython-3.xpicklesympydill

解决方案


而不是expr放入:funcdill.dump()

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

输出

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

推荐阅读