python - How can I add items to Context.data without loosing it once I exit the inner_function -


i having trouble python closures, hoping here help. below code.

import time multiprocessing import process   class context(object):      def __init__(self, x, y):         self.x = x         self.y = y         self.data = []   context = context(1, 2)   def test(text):      def inner_function():         in range(0, 10):             text.data.append(i)             time.sleep(1)             print(text.data.__len__())      thread = process(target=inner_function)     thread.daemon = true     thread.start()  test(context) time.sleep(12) print("final {0}".format(context.data.__len__())) 

the output seeing is

1 2 3 4 5 6 7 8 9 10 final 0 

i want final have value of 10. using python 2.7

your problem not closures sharing data between processes in thread works expected not pass data main process.

you return context explicity , maybe using pool.apply or apply_async right thing this.


Comments