Monkeypatching and multiprocessing. I have a class and I need to replace the object method by some other function (the idea of monkeypatching and I must do this because I will only know which function will be replaced at the runtime), then I need to use the multiprocessing for all the objects to call these function and do something (modify the value of attribute).
A simple example: I have a simple class called Test which has one attribute and one method called func
class Test:
def __init__(self):
self.attribute = 1
def func(self):
print("bye")
create two objects and put them in a list
a = Test()
b = Test()
c = [a, b]
define another function call func2
def func2(obj):
obj.attribute = obj.attribute + 1
print(obj.attribute)
print("hi")
replace the fun in object a by func2
a.func = types.MethodType(func2, a)
run the multiprocessing
def func123(x):
c[x].func()
return c[x]
if __name__ == '__main__':
pool = multiprocessing.Pool()
d = pool.map(func123, range(2))
pool.close()
Exception in thread Thread-3: AttributeError: 'Test' object has no attribute 'func2'
If I don't use multiprocessing and just simple call a.func, everything works fine. Also, If there is no return in the func123, the codes will work without error but it will not update the attribute value for object a.