ShashankAC
ShashankAC

Reputation: 1078

Multiprocessing pool with a method that requires more than one argument in python

I am new to multi-processing and python, from the documentation, https://docs.python.org/3/library/multiprocessing.html

I was able to run the below code.

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(f, [1, 2, 3]))

But if f(x) is changed to f(x,y,z) such that

def f(x, y, z):
        return x*y*z

What is the syntax to pass the 3 arguments to f(x, y, z) from the p.map method?

Upvotes: 1

Views: 54

Answers (2)

jtbandes
jtbandes

Reputation: 118681

Maybe you are looking for starmap?

starmap(func, iterable[, chunksize])

Like map() except that the elements of the iterable are expected to be iterables that are unpacked as arguments.

Hence an iterable of [(1,2), (3, 4)] results in [func(1,2), func(3,4)].

New in version 3.3.

Upvotes: 3

AKX
AKX

Reputation: 168986

Use p.starmap(), it's meant for exactly this case.

Upvotes: 1

Related Questions