I'm having problems sharing a dictionary of object instances with multiprocessing
. I'm trying to use a dict
that is share by a manager
, but when I try to use the object instance as a key, it gets copied.
import multiprocessing
class Dog():
def __init__(self, name = "joe"):
self.name = name
def bark(self):
print("woof")
mg = multiprocessing.Manager()
dt = mg.dict()
dt["a"] = 1
dt["b"] = 2
# As expected
print(dt.items()) # => [('a', 1), ('b', 2)]
dt = mg.dict()
lab = Dog("carl")
print(lab) # => <__main__.Dog instance at 0x7f8d6bb869e0>
dt[lab] = 1
# But then I don't get the ID I expect
print(dt.items()) # => [(<__main__.Dog instance at 0x7f8d6bb86908>, 1)]
I understand the way to work around this is to use object ID as a key, but why is this happening? Is using the object ID the best solution to my problem? I noticed that this doesn't happen with a normal non-manager
dict()
object.
Alternate approach
In the documentation for Manager()
, I read that some of the problem is informing the server of changes, so I changed my code to this, but I still have the same problem where my dogs are copied, not referenced.
import multiprocessing
class Dog():
def __init__(self, name = "joe"):
self.name = name
def bark(self):
print("woof")
mg = multiprocessing.Manager()
dt = dict()
lp = mg.list()
lp.append(dt)
print(lp)
dt["a"] = 1
dt["b"] = 2
lp[0] = dt
print(lp)
dt = dict()
lab = Dog("carl")
print(lab)
pup = Dog("steve")
print(pup)
dt[lab] = 1
dt[pup] = 2
lp[0] = dt
# Their ids change again
print(lp)