If I run a thread with the following function as the worker,
q = queue.Queue()
def worker():
while True:
t = {}
for i in range(3):
t['a'] = i
q.put(t)
the queue is populated with dictionaries that are all the same, i.e., {'a': 2}
instead of the sequence {'a': 0}, {'a': 1}, {'a': 2}
. I assume this is because the put()
method runs after the for loop has finished and the last value of i
was 2. Am I interpreting that right?
Now, if I move the instantiation of the dictionary inside the for loop,
def worker():
while True:
for i in range(3):
t = {'a': i}
q.put(t)
the queue is populated with the desired sequence. My interpretation is that in the first instance, I create a dictionary object in memory, then begin a for loop and reassign its value 3 times but the put()
calls happen after the loop has finished. In the second instance, I create a new dictionary object every iteration of the for loop and so when the put()
calls occur after the loop, they access 3 distinct instances of the dictionary with their own key-value pairs.
Can anyone shed some light on what's happening behind the curtain here?