I was reading up on deepcopy, and due to the use of memoization, it looks like deepcopies of the same mutable object all refer to the same object that resulted from the first deepcopy (if that makes sense). (Question and code below was inspired by this.)
from copy import deepcopy
a = [1,2,3]
memo = {}
b = deepcopy(a,memo)
print(memo)
# Output was
# {140324138116224: [1, 2, 3], 140324138884096: [[1, 2, 3]]}
# The ids that are the keys in the memo dictionary above may or may not be different
# every time you run the code. In any case, getting the key for value [1, 2, 3] below:
key = list(memo.keys())[0] # key is now 140324138116224 in this code run
Let's make another deepcopy of list "a". According to how memoization works, c is assigned the same object that b refers to.
c = deepcopy(a, memo) # So is this really another deepcopy of "a", intuitively speaking?
print(id(c) == id(b)) # Output is True, so "c" and "b" refer to the same object.
print(id(c) == id(memo[key])) # Output is True.
#According to the above link, "c" is created by memo.get(key),
# so it makes sense that the above returns True
b.append(4)
print(c) #We appended to "b", yet this will output [1, 2, 3, 4]
So if I want to make multiple deepcopies of a mutable object, it looks like I have to do
a = [1, 2, 3]
b = deepcopy(a, memo)
c = deepcopy(b, memo)
# etc.
like chain them together like that? Is there no other way? For example, what if I mutate "b" in between for some reason, like
a = [1, 2, 3]
b = deepcopy(a, memo)
# Do some mutating stuff to "b", like
b.append(4)
# Let's say I now want another deepcopy of "a", and not of "b", since I already did some stuff to "b".
c = deepcopy(a, memo)
# But the above seems to be not what I want because this will just give me a reference to the
# same object that "b" refers to.
print(c) # Gives [1, 2, 3, 4], which is not a copy of "a".
c = deepcopy(b, memo) # Not what I want either because I already did some mutating stuff to b
I know that in reality, I would do c = deepcopy(b, memo)
before mutating "b", but I was still wondering if there are any other ways possible to just be able to deal with copying mutable objects (with memo) more intuitively?
I suppose one could always not use memoization, in which case b = deepcopy(a)
and c = deepcopy(a)
will refer to different objects and are thus intuitive deepcopies of "a", but this seems like such a subtle difference in how to use deepcopy that results in drastically different results.
Thanks for any help!