They are invoked, but not directly by the language runtime, but by the copy
and deepcopy
functions of the copy
module of the library.
link
At the end of the documentation it is explained:
In order for a class to define its own copy implementation, it can
define special methods __copy__()
and __deepcopy__()
. The former is
called to implement the shallow copy operation; no additional
arguments are passed. The latter is called to implement the deep copy
operation; it is passed one argument, the memo dictionary. If the
__deepcopy__()
implementation needs to make a deep copy of a component, it should call the deepcopy () function with the component
the first argument and the memo dictionary the second argument.
Translating:
"For a class to define its own copy implementation, it can
define the special methods __copy__()
and __deepcopy__()
. O
first it is called for the operation of copy race; no argument
is passed. The latter is called to implement the
deep copy; is passed an argument, the dictionary of "memo." If the
__deepcopy__()
implementation needs to do a deep copy
of some other component, it should call the deepcopy()
function with
the first component and the "memo" dictionary as second
argument "
It is not mandatory for any system or code base to use the copy.copy
of the default library to copy its own objects, but if it does, the protocol is already set - and if everyone use, because of that protocol, the copies will work fine. If you try to use
django, and copying an instantiated object without using copy.copy
may have problems by not passing through the special methods defined in the objects.
Oh, just to demonstrate the calls, in the ipython terminal you can do:
In [19]: from copy import copy, deepcopy
In [20]: class Teste:
...: def __copy__(self):
...: print("copy")
...: return Teste()
...: def __deepcopy__(self, memo=None):
...: print("deepcopy")
...: return Teste()
...:
In [21]: copy(Teste())
copy
Out[21]: <__main__.Teste at 0x7f6c19e97fd0>
In [22]: deepcopy(Teste())
deepcopy
Out[22]: <__main__.Teste at 0x7f6c19e99e48>