I have
import copy
class A:
_member_a: dict[str, str]
_member_b: Callable
def set_b(self, func):
self._member_b = func
def deep_copy(self):
return copy.deepcopy(self)
I can set the value of _member_b with something like:
a = A()
a.set_b(some_actual_function_in_other_files)
and in another file, I have:
def some_actual_function_in_other_files(self):
# Implementation
def some_actual_function_in_other_files_2(self):
# Implementation
so in my test, I wrote:
def test(self):
a = A()
a._member_a = {"test", "test"}
a.set_b(some_actual_function_in_other_files)
copy = a.deep_copy()
self.assertIsNot(a._member_a, copy._member_a) # pass, because dictionary is mutable and deepcopy is not using the same reference
self.assertIsNot(a._member_b, copy._member_b) # fail, which means `a._member_b` and `copy._member_b` shares the same reference
I understand in copy.deepcopy(), if the object is immutable, Python just use copy the reference(e.g., integers). So in this case, is _member_b immutable?
I believe so, because later I updated the copy._member_b and I found a._member_b still has the original value which means it's not affected by the change of the copy. Is it true?
copy._member_band I founda._member_bstill has the original value which means it's not affected by the change of the copy.“ It sounds like you just overwrote the reference to a value, which is something you can do regardless of the value being referenced. For example, ints are immutable, but you can doa = 1and thena = 2no problem. Dicts are mutable, buta = b = {}andb = {"foo": "bar"}doesn’t seta.deepcopy()doesn't know how to make a copy of a function, so it just copies the reference.self.assertIsNot(a._member_b, copy._member_b)which fails.copy.deepcopy()? I would like to have the ability to construct a deep copy of an instance of class A, and the new copy is completely independent from the original one.copy.deepcopynot work for you needs, precisely?