views:

83

answers:

2

From the copy documentation:

Classes can use the same interfaces to control copying that they use to control pickling.

[...]

In order for a class to define its own copy implementation, it can define special methods __copy__() and __deepcopy__()

So which one is it? __setstate__() and __getstate__() that are used when pickling, or __copy__() and __deepcopy__()?

A: 

__setstate__() and __getstate__().

Notice that the copy documentation says that they can use the same interface, but they don't necessarily have do so.

See this excerpt from Python in a Nutshell, or this explanation on the Python Mailing List.

lfaraone
+4  A: 

It works as follows: if a class defines __copy__, that takes precedence for copy.copy purposes (and similarly __deepcopy__ takes precedence for copy.deepcopy purposes). If these very specific special methods are not defined, then the same mechanisms as for pickling and unpickling are tested (this includes, but is not limited to, __getstate__ and __setstate__; I've written more about this in my book "Python in a Nutshell" (which @ilfaraone quotes only partially).

Alex Martelli