Python Glossary Русский

all Python 3copyterm

Copy protocol

customization

The methods that customize how copy.copy() and copy.deepcopy() behave for your own classes.

Syntax

def __copy__(self): ...
def __deepcopy__(self, memo): ...

You rarely need these: by default copy rebuilds the object from its __dict__, which is enough almost always — hand-written versions appear when the object holds an uncopyable resource (socket, file handle, connection) or a cache that should start empty in the copy. Inside __deepcopy__, register the new object in memo under id(self) before copying anything, and copy nested fields via copy.deepcopy(x, memo) — otherwise cyclic references recurse forever and a shared sub-object gets duplicated instead of staying shared.

Examples

import copy
class MyObj:
    def __init__(self, v): self.v = v
    def __copy__(self):
        return MyObj(self.v)
    def __deepcopy__(self, memo):
        return MyObj(copy.deepcopy(self.v, memo))
obj = MyObj([1,2])
c = copy.copy(obj)
c.v is obj.v # → True  (shallow)
d = copy.deepcopy(obj)
d.v is obj.v # → False

See also

Open in the full glossarydocs.python.orgReport an inaccuracy