all Python 3copyfunction
__copy__
customization
The method copy.copy(obj) calls when it is defined: custom logic for a shallow copy.
Syntax
def __copy__(self): ...
Without __copy__ the copy module copies the object itself: it creates an instance of the same class and transfers its __dict__, leaving nested objects shared. A custom __copy__ is needed when part of the state must not or need not be copied: a connection, a cache, a counter. The method takes no arguments besides self.
Examples
import copy
class Doc:
def __init__(self, text):
self.text, self.cache = text, {'len': len(text)}
def __copy__(self):
return Doc(self.text) # кэш у копии свой, а не общий
a = Doc('abc')
b = copy.copy(a)
print(b.text, b.cache is a.cache) # → abc False
See also
Open in the full glossarydocs.python.orgReport an inaccuracy