3

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?

asked Aug 12, 2011 at 13:59
3
  • If any of the prop1, prop2 or prop3 are mutable (i.e. a list, dict, set, object etc as opposed to int, tuple, float, frozenset) then what you have above will result in a shared object and possibly result in bugs. a = [1,2,3]; b = a; b.append(4); print a results in [1,2,3,4] Commented Aug 12, 2011 at 14:05
  • What kind of object is it? What are the copies for? In Python, like other reference-semantic languages, it's usual to work around the value-copying problem by writing algorithms in a way that avoids the need for value-copying. Commented Aug 12, 2011 at 14:05
  • The correct name for the above function is shallow_copy. Commented Aug 12, 2011 at 14:07

1 Answer 1

2

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!

answered Aug 12, 2011 at 14:03
1
  • Yes, I've been thinking of profiling my code for awhile. I will try it out. Commented Aug 12, 2011 at 14:11

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.