Jul-30-2021, 10:40 PM
I've run across an issue with trying to copy an int argument for later use in the program. I realized the int that was copied is changing the value of the original argument; using id(val) and the copy id(valCopy), I can see that they have the same address. This isn't what I was expecting, as this is a simple int, not a list or similar. So, I did import copy, and used both copy.copy and copy.deepcopy, and all have the same result. I found that by modifying the copy, using +=1, then I get a new location, and no longer change the underlying.
I don't see any reference to having to do it this way, so I'm confused.
I'm using python version Python 3.8.10 (default, Jun 2 2021, 10:49:15) , but have also tried it on 3.10.x with same results.
I don't see any reference to having to do it this way, so I'm confused.
I'm using python version Python 3.8.10 (default, Jun 2 2021, 10:49:15) , but have also tried it on 3.10.x with same results.
import copy def a(val): newVal1 = val print("values: val: ", val, " newVal:", newVal1) print("addresses: val: ", id(val), " newVal:", id(newVal1)) newVal2 = copy.copy(val) print("values: val: ", val, " newVal:", newVal2) print("addresses: val: ", id(val), " newVal:", id(newVal2)) newVal3 = copy.deepcopy(val) print("values: val: ", val, " newVal:", newVal3) print("addresses: val: ", id(val), " newVal:", id(newVal3)) newVal1 += 1 print("values: val: ", val, " newVal:", newVal1) print("addresses: val: ", id(val), " newVal:", id(newVal1)) def main(): a(1) if(__name__ == '__main__'): main()
Output:values: val: 1 newVal: 1
addresses: val: 9476448 newVal: 9476448
values: val: 1 newVal: 1
addresses: val: 9476448 newVal: 9476448
values: val: 1 newVal: 1
addresses: val: 9476448 newVal: 9476448
values: val: 1 newVal: 2
addresses: val: 9476448 newVal: 9476480