I have a nested class:
class WidgetType(object): class FloatType(object): pass class TextType(object): pass
.. and an object that refers the nested class type (not an instance of it) like this
class ObjectToPickle(object): def __init__(self): self.type = WidgetType.TextType
Trying to serialize an instance of the ObjectToPickle class results in:
PicklingError: Can't pickle <class
'setmanager.app.site.widget_data_types.TextType'>
Is there a way to pickle nested classes in python?
Best Answer
I know this is a very old question, but I have never explicitly seen a satisfactory solution to this question other than the obvious, and most likely correct, answer to re-structure your code.
Unfortunately, it is not always practical to do such a thing, in which case as a very last resort, it is possible to pickle instances of classes which are defined inside another class.
The python documentation for the
__reduce__
function states that you can returnTherefore, all you need is an object which can return an instance of the appropriate class. This class must itself be picklable (hence, must live on the
__main__
level), and could be as simple as:All that is left therefore, is to return the appropriate arguments in a
__reduce__
method on FloatType:The result is a class which is nested but instances can be pickled (further work is needed to dump/load the
__state__
information, but this is relatively straightforward as per the__reduce__
documentation).This same technique (with slight code modifications) can be applied for deeply nested classes.
A fully worked example:
My final note on this is to remember what the other answers have said: