Python - How can I make this un-pickleable object pickleable?

So, I have an object that has a lot of weird things (pygame events, orderedDicts, clock, etc.) and I need to save it to disk.

Thing is, if I can just get this thing to save the line that has progress (one whole is all I need) then I can pass it to the init object and it will restore all of these things. Unfortunately, the framework I'm using (Renpy) will expand the object and try to load it, even though I could keep it as one and I can't change it.

So my question is, how can I override the methods so that whenever pickle tries to save the object, it only stores the progress value, and whenever it tries to load the object, it creates a new instance from the progress value?

I've seen a bit of the __repr__ method talker, but I'm not sure how I would use that in my situation.

+3


source to share


1 answer


The hook you are looking for is __reduce__

. It must return a tuple (callable, args)

; callable

and args

will be serialized, and upon deserialization, the object will be recreated via callable(*args)

. If your class constructor accepts int, you can implement __reduce__

as

class ComplicatedThing(object):
    def __reduce__(self):
        return (ComplicatedThing, (self.progress_int,))

      



There are a few extra extra things you can put in a tuple, mostly useful when the object graph has circular dependencies but you don't need it here.

+5


source







All Articles