I am trying to pass the keyword arguments to the map
function in Python's multiprocessing.Pool
instance.
Extrapolating from Using map() function with keyword arguments, I know I can use functools.partial()
such as the following:
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)
The output is correct:
0
2
4
6
8
10
12
14
16
18
Is this the best practice (most "pythonic" way) to do so? I felt that:
1) Pool
is commonly used;
2) Keyword arguments are commonly used;
3) But the combined usage like my example above is a little bit like a "hacky" way to achieve this.