I've made a minimalistic example that shows that python multiprocessing errors when wrapped inside a function for some reason. Is there any way around this?
This code works:
from multiprocessing import Pool
import time
def _foo(my_number):
square = my_number * my_number
time.sleep(1)
return square
with Pool() as p:
r = list(p.imap(_foo, range(10)))
print(r)
This code doesn't:
from multiprocessing import Pool
import time
def test():
def _foo(my_number):
square = my_number * my_number
time.sleep(1)
return square
with Pool() as p:
r = list(p.imap(_foo, range(30)))
print(r)
test()
It errors out with the message AttributeError: Can't pickle local object 'test.<locals>._foo'
.
There've been other questions related to this, but I'm pretty sure this doesn't infract any of those. In particular, Pool()
is started after everything it needs (_foo
).
So how should one call multiprocessing from within a function using something defined in that function?