Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pickle call constructor

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?

like image 988
c z Avatar asked Jan 12 '17 15:01

c z


People also ask

Does pickle call init?

__init__ isn't called When the pickle module recreates your objects, it does not call your __init__ method, since the object has already been created. This can be surprising, since nowhere else do objects come into being without calling __init__.

What is pickle dump ()?

Python Pickle dump dump() function to store the object data to the file. pickle. dump() function takes 3 arguments. The first argument is the object that you want to store. The second argument is the file object you get by opening the desired file in write-binary (wb) mode.

How do you load data with pickles?

The process of loading a pickled file back into a Python program is similar to the one you saw previously: use the open() function again, but this time with 'rb' as second argument (instead of wb ). The r stands for read mode and the b stands for binary mode. You'll be reading a binary file. Assign this to infile .

How do I Unpickle a pickle file?

As we said earlier, the load() method can be used to unpickle the pickled Python object. You have to first open the pickled file using rb (read-binary) permission and pass the opened file to the load() method, as shown below. The load() method unpickles the data and returns the actual object.


1 Answers

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.

like image 100
jlh Avatar answered Sep 20 '22 07:09

jlh