我试图将关键字参数传递给Python的multiprocessing.Pool
实例中的map
函数。使用带有关键字参数的multiprocessing.Pool.map()函数?
从Using map() function with keyword arguments推断,我知道我可以使用functools.partial()
如下列:
from multiprocessing import Pool
from functools import partial
import sys
# Function to multiprocess
def func(a, b, c, d):
print(a * (b + 2 * c - d))
sys.stdout.flush()
if __name__ == '__main__':
p = Pool(2)
# Now, I try to call func(a, b, c, d) for 10 different a values,
# but the same b, c, d values passed in as keyword arguments
a_iter = range(10)
kwargs = {'b': 1, 'c': 2, 'd': 3}
mapfunc = partial(func, **kwargs)
p.map(mapfunc, a_iter)
输出是正确的:
0
2
4
6
8
10
12
14
16
18
这是最好的做法(最 “Python的” 方式)这样做?我觉得:
1)Pool
是常用的;
2)关键字参数是常用的;
3)但是,像我上面的例子一样的组合使用有点像一个“哈克”的方式来实现这一点。
对我来说似乎很好。 map只需要位置参数,所以使用partial来创建合适的函数对象是非常合理的。 – nneonneo