Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Value by reference issue
#1
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.

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
Reply


Messages In This Thread
Value by reference issue - by javaben - Jul-30-2021, 10:40 PM
RE: Value by reference issue - by bowlofred - Jul-30-2021, 11:32 PM
RE: Value by reference issue - by javaben - Jul-30-2021, 11:59 PM
RE: Value by reference issue - by javaben - Jul-31-2021, 02:36 AM
RE: Value by reference issue - by bowlofred - Jul-31-2021, 12:22 AM
RE: Value by reference issue - by deanhystad - Jul-31-2021, 12:24 AM
RE: Value by reference issue - by deanhystad - Jul-31-2021, 04:47 AM
RE: Value by reference issue - by javaben - Jul-31-2021, 04:48 AM
RE: Value by reference issue - by deanhystad - Jul-31-2021, 04:59 AM
RE: Value by reference issue - by javaben - Jul-31-2021, 12:55 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Pass by object reference when does it behave like pass by value or reference? mczarnek 2 2,566 Sep-07-2020, 08:02 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020