3

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 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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) 

Comments

1

Just use starmap because map supports only one iterable argument https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.starmap

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.