Search code examples
pythonpython-3.xaliaspython-class

Best way to copy data attributes between different instances of a class


I'm writing a program that requires the copying of a data attribute from one instance of a class to another. At first, this was implemented using deepcopy(), creating a duplicate instance within the local scope of a function, which is then discarded upon function termination. The problem is, this is used for an important aspect of the program that will be repeated many times. I'm afraid deepcopy() will slow the program down horribly.

My alternative solution was to set the data attribute of the second instance via:

instance2.dataattribute = instance1.dataattribute

I believe this creates an aliasing problem, where changes to instance1 are also made to instance2.

What is the most efficient way to copy a data attribute to another instance of the same class?


Solution

  • You have three choices: assignment, shallow copy, and deep copy. Assignment is fine when the attribute is immutable. Shallow copy (copy.copy) works for mutable attributes with immutable fields only (e.g., a list of integers). Deep copy (copy.deepcopy) is appropriate for mutable attributes containing mutable fields (e.g., a list of lists). Here is a very helpful article on the topic.