I have seen some SO questions on making dictionaries which reference other parts of the same dictionary, but they all seem to be for static returns whenever the dictionary is first created. Is there a way to do this and stay dynamic?
Like so:
# Lets just say we have a barn with lots of animals
# and the pigs always eat 2 chickens, so there has to always be 2 chickens per pig
def make_barn():
barn = {'pig': 0, 'cow': 0, 'chicken': 2*barn['pig']}
return barn
Such that this:
barn['pig'] = 3
print barn
will print this:
{'pig':3, 'chicken':6, 'cow':0}
I tried using lambda functions or classes, but I am trying to pickle this as a HUGE dictionary for the purpose of passing in between processes in the multiprocessing
module and that module didn't seem to like lambda
or class
structures.
Edit:
I tried using the answer given in a multiprocessing script and it appears that it isn't picklable:
import multiprocessing as mp
import random
from UserDict import UserDict
class Barn(UserDict):
'''Barn automatically sets correct values for chickens.
TBD: What to do if chickens get changed?'''
def __init__(self, *args, **kw):
UserDict.__init__(self, *args, **kw)
pigs = self.data.get('pigs', None)
if pigs is not None:
self.data['chicken'] = pigs * 2
def __setitem__(self, name, value):
if name == 'pigs':
self.data['chicken'] = value * 2
self.data[name] = value
def count_animals(barn_record):
for animal in random.randrange(0,10,1):
barn_record['pigs'] = animal
# We need this to 'if __name__ == '__main__':' business to avoid having too many farms created continuously
# See here : https://stackoverflow.com/questions/1923706/multiprocessing-launching-too-many-instances-of-python-vm
if __name__ == '__main__':
manager = mp.Manager()
barn_record = manager.dict({'pigs':3,'cows':2})
farm = mp.Process(target = count_animals, args=(manager,))
farm.start()
print barn_record