I do several request to a database about shortest paths, very often the same ones (76 iterations, and for each iteration 10'000 to 20'000 requests; and I run this several times with small differences but mostly the same origins and destinations of the shortest path). So I created a cache. My cache is a dictionary.
with open('path_to_OD_dict', 'rb') as file:
my_unpickler=pickle.Unpickler(file)
OD_dict = my_unpickler.load()
Origins and destinations are coded with a 5-digit number. I fill them with zeros if necessary, and then put them together (we have origin_route < destination_route):
origin_route = str(origin_route).zfill(5)
destination_route = str(destination_route).zfill(5)
key = origin_route + destination_route
Then I simply try to find this key I just built in my dictionary. If it exists, I have directly my value.
try:
result = OD_dict[key]
Otherwise, I request the shortest path and add it in the dictionary:
except:
result = shortestPathLength(origin_route, destination_route)
OD_dict[key] = result
with open('path_to_OD_dict', 'wb') as file:
my_pickler=pickle.Pickler(file)
my_pickler.dump(OD_dict)
At the line OD_dict[key] = result
I have the mistake TypeError: 'str' object does not support item assignment
.
I'm also using Multiprocessing
. It is very likely that I'm just trying to access OD_dict
with several processes at the same time.
results = []
po = multiprocessing.Pool()
for item in aSet:
results.append(po.apply_async(aBiggerFunctionWithShortestPathInIt))
po.close()
po.join()
for r in results:
myResult.add(r.get())
Why do I get this particular message? (TypeError)
Plus, how should I adapt my code to be able to read OD_dict
with several processes at the same time (or at least without creating a problem), and modify it if necessary sequentially, without modifying the dump simultaneously?