0

Noticed that when a passed parameter is an object, making a copy of the parameter and changing the copy attribute's value also changes the original attribute's value (Shallow Copy). However, when the passed object is a simple variable, creating and changing the copy's value does not change the original (Deep Copy).

Example:

1. Variable passed as argument

def increment(x):
    y = x
    y += 1
    print(f'{x=}, {y=}')
increment(2)
Out: 
x=2, y=3

x did not change when it's copy y was incremented

2. Object passed as argument

class Node:
    def __init__(self, val=0):
        self.val = val

def increment(x):
    y = x
    y.val += 1
    print(f'{x.val=}, {y.val=}')
increment(Node(2))
Out: 
x.val=3, y.val=3

x.val was also incremented when copy y.val was incremented.

What is the best (computationally time-efficient) way to go about creating a deep copy of the object? Can I write the class in a way such that I don't have to make any changes in the function code?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Shash
  • 1
  • 1
    The answer to your second question is no. There's no way to make a class that can detect when it's being assigned to a new variable. Python simply doesn't support that. – Silvio Mayolo Jul 28 '21 at 02:07
  • Possible duplicate. Take a look at [this answer](https://stackoverflow.com/a/10452866). – Manuel García Apr 03 '22 at 13:09
  • @ManuelGarcía this doesn't have anything to do with lambdas, closures or late binding; but it *is* a common duplicate. – Karl Knechtel Aug 19 '22 at 13:01
  • There isn't a difference between "objects" and "variables" here - you can't actually pass "variables"; you pass a **value** - which are the result of evaluating an **expression** (and a variable name by itself is one kind of expression). Values in Python are all objects. The difference here is between *reassigning* a name, versus *mutating the object* with that name. You can, of course, avoid the problem by making a copy. Please see the linked duplicate - `y = x` **does not copy, not even a shallow copy**. You may, however, not always need a deep copy. Your example only needs a shallow copy. – Karl Knechtel Aug 20 '22 at 01:34

0 Answers0