Bharathwaaj Bharathwaaj - 9 months ago 31
Python Question

Priority Queue and Mutability

>>> import Queue
>>> q = Queue.PriorityQueue()
>>> a = (1, {'item': 'value'})
>>> q.put(a)
>>> q.queue
[(1, {'item': 'value'})]
>>> a[1]['count'] = 1
>>> q.queue
[(1, {'count': 1, 'item': 'value'})]
>>> q.get()
(1, {'count': 1, 'item': 'value'})


Why the value in queue changes when the value of 'a' is changed after adding? The tuple by itself is immutable but the dictionary present inside is mutable. But I couldn't understand why the queue should get altered?

Answer Source

In Python, objects are passed by reference. Some objects may appear to be passed as values (such as strings and integers), but that is because those objects are immutable (e.g. you can't change the value of the integer object 1).

So when you place a dictionary in the queue, it is the actual dictionary that will pop out the other other end rather than a copy.

You can use the dictionary's copy() method if you want a copy, but note that it will only give you a shallow copy of the dictionary: the keys and values in the copy will be the same objects and they may be mutable themselves.