python - 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!
解决方案
而不是expr
放入:func
dill.dump()
with open('expr', 'wb') as outf:
dill.dump(func, outf)
输出
<function <lambda> at 0x7fd3015c4510>
<class 'function'>
12
推荐阅读
- mysql - 使用每个电影类型的平均排名作为指标的顶级电影类型是什么?
- javascript - 隔离 angularjs 匿名 $parser:ueoe 错误
- javascript - 将带有 css 或 js 的 Canvas 缩放到屏幕的最佳方法是什么?以及如何使画布的宽度等于高度?
- css - 确保无论文本长度如何,我的引导表中的两行始终并排
- laravel - Laravel 控制器中的 API 调用
- javascript - focus() 在 Chrome 中的 getUi().showSidebar html 中不起作用
- python - 当您在网页上做出一些选择时,如何找到正确的 URL?
- visual-studio-code - Vs 代码终端是空白的,我无法输入
- python - 如何在pyqt中运行另一个程序时使QProgressBar显示更新
- python-3.x - BeautifulSoup4 - 在批处理 url 的两个不同标签之间连接多个 html 元素