Sometimes I need to use multiprocessing with functions with no arguments. I wish I could do something like:
from multiprocessing import Pool
def f(): # no argument
return 1
# TypeError: f() takes no arguments (1 given)
print Pool(2).map(f, range(10))
I could do Process(target=f, args=())
, but I prefer the syntax of map
/ imap
/ imap_unordered
. Is there a way to do that?
The ordering of results from the returned iterator of imap_unordered is arbitrary, and it doesn't seem to run faster than imap (which I check with the following code), so why would one use this method? In this example, the difference between the amount of time required for 0**2 is not that different from 49**2 .
The map function has two arguments (1) a function, and (2) an iterable. Applies the function to each element of the iterable and returns a map object. The function can be (1) a normal function, (2) an anonymous function, or (3) a built-in function.
imap is from itertools module which is used for fast and memory efficiency in python. Map will return the list where as imap returns the object which generates the values for each iterations(In python 2.7). The below code blocks will clear the difference. imap returns object which is converted to list and printed.
Unlimited Number of Positional Argument ValuesPython lets us define a function that handles an unknown and unlimited number of argument values. Examples of built-in functions with a unlimited number of argument values are max and min .
You can use pool.starmap()
instead of .map()
like so:
from multiprocessing import Pool
def f(): # no argument
return 1
print Pool(2).starmap(f, [() for _ in range(10)])
starmap
will pass all elements of the given iterables as arguments to f
. The iterables should be empty in your case.
map
function's first argument should be a function and it should accept one argument. It is mandatory because, the iterable passed as the second argument will be iterated and the values will be passed to the function one by one in each iteration.
So, your best bet is to redefine f
to accept one argument and ignore it, or write a wrapper function with one argument, ignore the argument and return the return value of f
, like this
from multiprocessing import Pool
def f(): # no argument
return 1
def throw_away_function(_):
return f()
print(Pool(2).map(throw_away_function, range(10)))
# [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
You cannot use lamdba
functions with pools because they are not picklable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With