Reputation: 165
I'm having a problem with two objects I created. I have a while loop getting some data. I save this data in an object and on each loop I want to see if my data has changed. If its true I save the data on a log. The problem is that when I refresh my actVar my prevVar is getting this changed too. This is my code:
I tried to use the copy() function with no success
uvcomsSup = UVCEComsCtrl_SupportData()
uvcomsAntSup = UVCEComsCtrl_SupportData()
while 1:
try:
uvcomsSup = getUVComsSupport(OrigAddress, UVComsDestAddress)
print(uvcomsSup)
print("________________________")
print(uvcomsAntSup)
print(uvcomsSup is uvcomsAntSup)
if (uvcomsSup != uvcomsAntSup):
uvcomsAntSup = copy.copy(uvcomsSup)
logFile.addSupportData(str(uvcomsSup))
sleep(1)
except Exception as err:
print("Error inesperado:", sys.exc_info()[0])
print(err)
When I print this two objects (I have an eq method and str method) I see the same values. I just enter in the if condition the first time.
Any help?
Thank you
Upvotes: 0
Views: 352
Reputation: 1245
The Python docs say:
copy(x) Return a shallow copy of x.
A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
Try using copy.deepcopy(x) instead.
uvcomsAntSup = copy.deepcopy(uvcomsSup)
copy.deepcopy(x) Return a deep copy of x.
A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
Read more about this: https://docs.python.org/3.7/library/copy.html
Upvotes: 0
Reputation: 1068
I cannot run your code so I cannot see the whole picture.
However I can see you are returning a shallow copy of ucomsSup
, which retains references to the original object thus modifying it.
Try using a deep copy instead.
uvcomsSup = UVCEComsCtrl_SupportData()
uvcomsAntSup = UVCEComsCtrl_SupportData()
while 1:
try:
uvcomsSup = getUVComsSupport(OrigAddress, UVComsDestAddress)
print(uvcomsSup)
print("________________________")
print(uvcomsAntSup)
print(uvcomsSup is uvcomsAntSup)
if (uvcomsSup != uvcomsAntSup):
uvcomsAntSup = copy.deepcopy(uvcomsSup) ## Create deep copy
logFile.addSupportData(str(uvcomsSup))
sleep(1)
except Exception as err:
print("Error inesperado:", sys.exc_info()[0])
print(err)
Upvotes: 1