Search code examples
pythonpython-3.xcopydeep-copy

copy vs deepcopy: semantics


My class represents states of various systems. Each instance has two attributes: one is a container shared between all the states of the same system, and the other is a container that is unique to each instance.

A copy of a state should reuse the "shared" attribute, but create a deep copy of the "unique" attribute. This is really the only copy semantics that makes sense (it's natural that the copy of a state is a state of the same system).

I want to create the least surprise for people who read and maintain my code. Should I override __deepcopy__ or __copy__ for my purposes?


Solution

  • Is it really necessary to use the copy module for copying instances of this class? I would argue that instead of overriding __copy__ or __deepcopy__ you should create a copy method for your class that returns a new object using the copy semantics you defined.

    If for some consistency reason you do need to use the copy module, then in my opinion __deepcopy__ is more appropriate. If it is a defined behavior of the class that all instances share one of the containers, then it is reasonable to assume that an implementation of __deepcopy__ would respect that.