Passing sympy lambda to multiprocessing.Pool.map

孤街醉人 提交于 2019-12-05 09:23:58

The object Mult has no fields when it is created. It can thus be pickled with the stock pickle library. Then, when you call lambdify, you add a _lambdify attribute to the object containing a lambda expression, which cannot be pickled. This causes a failure in the map function

This explains why before calling lambdify you can pickle the object and use Pool.map and why it fails after the call. When you uncomment the line in lambdify, you do not add the attribute to the class, and the Mult object can still be pickled after calling lambdify.

Though I have not fully explored this yet, I just want to put on record that the same example works just fine when using loky instead of multiprocessing:

from loky import get_reusable_executor

import sympy
from sympy.abc import x

def f(m):
    return m.lambdify()(1)

class Mult():
    def lambdify(self):
#        return sympy.lambdify(x, 2*x, 'numpy')
        self._lambdify = sympy.lambdify(x, 2 * x, 'numpy')
        return self._lambdify


executor = get_reusable_executor()

m = Mult()
print('pool.map(f, [m])', list(executor.map(f, [m])))
print('pool.map(f, [m])', list(executor.map(f, [m])))
print('f(m)', f(m))
print('pool.map(f, [m])', list(executor.map(f, [m])))

with output

pool.map(f, [m]) [2]
pool.map(f, [m]) [2]
f(m) 2
pool.map(f, [m]) [2]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!