Python - How can I make this un-pickleable object pickleable?
Solution 1:
The hook you're looking for is __reduce__
. It should return a (callable, args)
tuple; the callable
and args
will be serialized, and on deserialization, the object will be recreated through callable(*args)
. If your class's constructor takes an int, you can implement __reduce__
as
class ComplicatedThing:
def __reduce__(self):
return (ComplicatedThing, (self.progress_int,))
There are a few optional extra things you can put into the tuple, mostly useful for when your object graph has cyclic dependencies, but you shouldn't need them here.