Copy and deep copy: semantics

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

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

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

+6
source share
2 answers

Is it really necessary to use a copy module to copy instances of this class? I would say 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 that you defined.

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

+3
source

Does this look like your situation?

 import copy class Foo(object): shared = [[]] def __init__(self): self.perinstance = [[]] 

If so, then you do not need to define __copy__ or __deepcopy__ , since the default behavior of copy.deepcopy separates class attributes and instance attributes of deepcopies:

 x = Foo() z = copy.deepcopy(x) assert id(z.shared) == id(x.shared) assert id(z.shared[0]) == id(x.shared[0]) assert id(z.perinstance) != id(x.perinstance) assert id(z.perinstance[0]) != id(x.perinstance[0]) 
0
source

Source: https://habr.com/ru/post/913753/


All Articles