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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With