Using pool.map to run multiple functions in Python

Viewed 749

I need to run in parallel multiple functions. I tried this

from multiprocessing import Pool

def smap(f, *args):
    return f(*args)

def somma(*args):
    a=args[0]
    b=args[1]
    return a+b

def prodotto(*args):
    a=args[0]
    b=args[1]
    return a*b

pool = Pool(processes=2)
a=2
b=4
res=pool.map(smap, [(somma,a,b),(prodotto,a,b)])
print(res)

with the following error:

TypeError: 'tuple' object is not callable

What's wrong?

3 Answers

You are passing the entire tuple as the first argument f to function smap, which is not a function as you intended. You can change smap to:

def smap(f_args):
    f, *args = f_args
    return f(*args)

This will correctly accept only one argument from Pool.map and split f and args inside the call.

You are expecting the pool.map internals to do the unpacking in smap for you but this is something which the logic cannot handle. You need to explicitely do it yourself.

def smap(params): 
    function, *args = params 

    return function(*args) 
Related