I have a method inside a class that needs to do a lot of work in a loop, and I would like to spread the work over all of my cores.
I wrote the following code, which works if I use normal map()
, but with pool.map()
returns an error.
import multiprocessing
pool = multiprocessing.Pool(multiprocessing.cpu_count() - 1)
class OtherClass:
def run(sentence, graph):
return False
class SomeClass:
def __init__(self):
self.sentences = [["Some string"]]
self.graphs = ["string"]
def some_method(self):
other = OtherClass()
def single(params):
sentences, graph = params
return [other.run(sentence, graph) for sentence in sentences]
return list(pool.map(single, zip(self.sentences, self.graphs)))
SomeClass().some_method()
Error 1:
AttributeError: Can't pickle local object 'SomeClass.some_method..single'
Why can't it pickle single()
? I even tried to move single()
to the global module scope (not inside the class - makes it independent of the context):
import multiprocessing
pool = multiprocessing.Pool(multiprocessing.cpu_count() - 1)
class OtherClass:
def run(sentence, graph):
return False
def single(params):
other = OtherClass()
sentences, graph = params
return [other.run(sentence, graph) for sentence in sentences]
class SomeClass:
def __init__(self):
self.sentences = [["Some string"]]
self.graphs = ["string"]
def some_method(self):
return list(pool.map(single, zip(self.sentences, self.graphs)))
SomeClass().some_method()
and I get the following ...
Error 2:
AttributeError: Can't get attribute 'single' on module 'main' from '.../test.py'
delex
as an argument (which you canfunctools.partial
) instead of capturing the value. Your modified version should have worked fine; the question is why it's looking indata.SomeClass.reader
, which doesn't seem like a module at all, instead of in the module, which is presumablydata
. Can you give us a minimal reproducible example for that version? – Jesuitismdata.SomeClass.reader
is because that is the file's hirarchy as I have multiple data sources and a reader for each. I removed that, and instead just wrote a new class that has the same error. – Constant