4

I was working with queue in python when I had a error in code even while the code looked very perfect to me but latter when I changed assignment style all of sudden the code started working. The code looked some what like this before.

    x=y=Queue()
    x.put("a")
    x.put("b")
    print y.get()

later i changed to this and it started working

    x=Queue()
    y=Queue()
    x.put("a")
    x.put("b")
    print y.get(10)

why do both code work differently?

Sar009
  • 2,166
  • 5
  • 29
  • 48
  • Because in `x=y=Queue()` `x` and `y` are references to the same object. – Ashwini Chaudhary Sep 28 '13 at 13:06
  • 2
    Also, note that `y.get(10)` is probably not what you want. The first parameter to [`Queue.get()`](http://docs.python.org/3.3/library/queue.html#queue.Queue.get) is `block`, which is interpreted as a `bool`. – Sam Mussmann Sep 28 '13 at 13:24

2 Answers2

13

Variables in Python are references, or names, not like variables in C etc.

This code:

x=y=Queue()

means "allow the name y to reference an object in memory made by calling Queue(), and allow the name x to reference the object that y is pointing to." This means both variables refer to the same object - as you can verify with id(x) == id(y).

This code:

x=Queue()
y=Queue()

means "allow the name x to reference one object made by Queue(), and allow the name y to reference another object made by Queue()". In this case, id(x) == id(y) is False

This can often bite you:

a = [1,2,3,4,5]
b = a
b.append(6)
print(a)
# [1,2,3,4,5,6] even though we didn't seem to do anything to a!

To get around this, do import copy; b = a.copy(); instead of b = a.

However, this behaviour doesn't occur to immutable objects like integers:

a = 7
a += 1

This doesn't go to the object that a is referencing and change it by adding one, instead it dereferences a from the object 7, and references it to the object representing the previous value of a + 1 (that is to say, 8). This is unlike actions performed on mutable objects, like lists in the previous example - appending to a list does change the object that the variable is referencing.

So we can do this:

a = 7
b = a
a += 1
print(a)
# 8
print(b)
# 7
rlms
  • 10,650
  • 8
  • 44
  • 61
3

Your first code is actually equivalent to:

y=Queue()
x=y
x.put("a")
x.put("b")
print y.get()

Which is different than your second example, because Python handles object by reference. After x=y both variables x and y refer to the same object. In your second example you have two independent queues.

zch
  • 14,931
  • 2
  • 41
  • 49