Suppose I have two classes, say Manager and Graph, where each Graph has a reference to its manager, and each Manager has references to a collection of graphs that it owns. I want to be able to do two things
1) Copy a graph, which performs a deepcopy except that the new graph references the same manager as the old one.
2) Copy a manager, which creates a new manager and also copies all the graphs it owns.
What is the best way to do this? I don’t want to have to roll my own deepcopy implementation, but the standard copy.deepcopy doesn’t appear to provide this level of flexibility.
If there are no other objects referenced in graph (just simple fields), then
copy.copy(graph)should make a copy, whilecopy.deepcopy(manager)should copy the manager and its graphs, assuming there is a list such asmanager.graphs.But in general you are right, the
copymodule does not have this flexibility, and for slightly fancy situations you’d probably need to roll your own.