Python - How Can I Make This Un-pickleable Object Pickleable?
So, I have an object that has quite a bit of non-pickleable things in it (pygame events, orderedDicts, clock, etc.) and I need to save it to disk. Thing is, if I can just get this
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
classComplicatedThing: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.
Post a Comment for "Python - How Can I Make This Un-pickleable Object Pickleable?"