Python dunders __copy__ e __deepcopy__

Asked

Viewed 83 times

2

I’ve seen it in some codes, especially Django dunders __copy__ and __deepcopy__, the idea by traś them I understand that provide copies of the object, but usually the dunders can be called "especial" some examples would be the len() invoca __len__, == invoca __eq__ my question is these dunders have a way "especial" to be invoked?

1 answer

4


They are invoked, but not directly by the language, but by the functions copy and deepcopy module copy of the library Pedron:

https://docs.python.org/3/library/copy.html

At the end of the documentation 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 as first argument and the memo Dictionary as Second argument.

Translating:

"For a class to define its own copy implementation, it can define the special methods __copy__() and __deepcopy__(). The first is called for the Raza copy operation; no argument additional is passed. The latter is called to implement the operation of deep copy; is passed an argument, the dictionary of "memo". If the implementation of __deepcopy__() need to make a deep copy of some other component, it should call the function deepcopy() with the component as primeirio and the dictionary of "memo" as second argument"

Is not obligatory that any system or code base uses the copy.copy from the standard library to copy your own objects, but if it does, the protocol is already set - and if everyone uses, because of this protocol, the copies will work fine. If you try to use Django, and copy an instantiated object without using the copy.copy may have problems not passing the special methods defined in the objects.

Ah, just to demonstrate the calls, at 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>
  • Again excellent explanation. Thank you jsbueno.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.