Python Glossary Русский

all Python 3copyfunction

__deepcopy__

customization

The method copy.deepcopy(obj) calls: a custom deep copy. It receives the memo dict of what has already been copied.

Syntax

def __deepcopy__(self, memo): ...

memo maps id(original) to copy: pass it on to nested deepcopy calls, otherwise circular references recurse forever and shared objects get duplicated. Record your own copy in memo before copying fields — then a reference from the object to itself resolves too.

Examples

import copy
class Node:
    def __init__(self, items):
        self.items = items
    def __deepcopy__(self, memo):
        clone = Node(None)
        memo[id(self)] = clone
        clone.items = copy.deepcopy(self.items, memo)
        return clone
a = Node([[1, 2]])
b = copy.deepcopy(a)
b.items[0].append(3)
print(a.items, b.items)  # → [[1, 2]] [[1, 2, 3]]

See also

Open in the full glossarydocs.python.orgReport an inaccuracy