How can I create a copy of an object in Python?

Roman picture Roman · Jan 25, 2011 · Viewed 179.9k times · Source

I would like to create a copy of an object. I want the new object to possess all properties of the old object (values of the fields). But I want to have independent objects. So, if I change values of the fields of the new object, the old object should not be affected by that.

Answer

Sven Marnach picture Sven Marnach · Jan 25, 2011

To get a fully independent copy of an object you can use the copy.deepcopy() function.

For more details about shallow and deep copying please refer to the other answers to this question and the nice explanation in this answer to a related question.