I'd like to provide defaults for missing values using Python's pickle serialiser. Since the classes are simple, the defaults are naturally present in the classes's __init__
methods.
I can see from pickle documentation that there is __getnewargs__
. However, this only works for cases where __getnewargs__
was present prior to "pickling".
Is there any way to tell python pickle to call always the constructor rather than starting with an uninitialised object?
Unpickling will always create an instance without calling __init__()
. This is by design. In python 2 it was possible to override __getinitargs__()
to cause unpickling to call __init__()
with some arguments, but it was necessary to have had this method overridden at pickling time. This is not available in python 3 anymore.
To achieve what you want, wouldn't it be enough to just manually call self.__init__()
from self.__setstate__(state)
? You can provide any default arguments not found in state
.