Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: copying objects with copy.deepcopy or writing my own copy

Currently I am using the copy module to create a copy of some object that I have.

Under certain conditions (that occur frequently), I will need to create possibly several copies of the original object, and then modify each of them individually (hence why I am using copy).

The object has several instances of various datatypes (lists, ints, strings, other classes), and the copies need to have the same values, but I am not sure whether it would faster to call copy.deepcopy(), or do something like

def copy(self, other):
   other.prop1 = self.prop1
   other.prop2 = self.prop2
   other.prop3 = self.prop3

Has anyone run into this problem and then decided it was better to use the copy module because it would be faster than anything most people could come up with?

PS: the code above wouldn't properly copy mutable objects and those "other classes" that I mentioned. Perhaps that suggests deepcopy is the safest (and fastest) route?

like image 847
MxLDevs Avatar asked Jan 18 '26 16:01

MxLDevs


1 Answers

Not trying to be glib, but have you considered profiling your code? Documentation here. Compare copy.deepcopy with with your own custom copy method. That way you'll have hard data on your particular situation and can make the best decision--and back it up if anyone asks why you did it that way!

like image 79
sandinmyjoints Avatar answered Jan 21 '26 07:01

sandinmyjoints