I know that in order to be picklable, a class has to overwrite __reduce__
method, and it has to return string or tuple.
How does this function work?
What the exact usage of __reduce__
? When will it been used?
I know that in order to be picklable, a class has to overwrite __reduce__
method, and it has to return string or tuple.
How does this function work?
What the exact usage of __reduce__
? When will it been used?
I'll see if I can take a stab at explaining this one.
Whenever you try to pickle an object, there will be some properties that may not serialize well. For instance, an open file handle In this cases, pickle won't know how to handle the object and will throw an error.
You can tell the pickle module how to handle these types of objects natively within a class directly. Lets build the example of an object which has a single property; an open file handle:
It should fail, and give a traceback:
However, had we defined a
__reduce__
method in ourtest
class
, pickle would have known how to serialize this object:This should give you something like:
"c__main__\ntest\np0\n(S'test1234567890.txt'\np1\ntp2\nRp3\n."
, which can be used to recreate the object with open file handles:Usually, the big confusion is with what type of object
__reduce__
should return. while you can read a little more about what type of object reduce should return in the docs pages: http://aakashlabs.org/docs/apl/pyhelp/pydocs/library/pickle.html#pickling-and-unpickling-extension-types, but in general, it needs a tuple of at least 2 things:self.__class__
There are other optional items, but you should read all about them in the docs.
Hope that helps!