Pickle __getstate__ __setstate__ and restoring n/w - beazley pg 172

dieter dieter at handshake.de
Thu Mar 10 03:06:06 EST 2016


"Veek. M" <vek.m1234 at gmail.com> writes:
> ...
> what i wanted to know was, x = Client('192.168.0.1') will create an 
> object 'x' with the IP inside it. When I do:
> pickle.dump(x)
> pickle doesn't know where in the object the IP is, so he'll call 
> __getstate__ and expect the return value to be the IP, right?

It does not expect anything. It pickles, whatever "__getstate__"
returns. The unpickling will fail (either
explicitely or implicitely), when "__setstate__" does not "fit"
with "__getstate__" or does not restore the state in the way
you expect.

> Similarly, whilst unpickling, __setstate__ will be called in a manner 
> similar to this:
> x.__setstate__(self, unpickledIP)

Yes.

> __setstate__ can then populate 'x' by doing 
> self.x = str(unpickledIP)
>
> the type info is not lost during pickling is it, therefore 'str' is not 
> required is it? 

Yes.

Note however, that "__setstate__" is called automatically
during "unpickling". No need that you do this yourself.


You can also easily try out things yourself (e.g. in
an interactive Python session). The builtin "vars" allows you
to look into an object. As an example, you could do:

       client = Client(...)
       vars(client)
       pickle.dump(client, open(fn, "wb"))
       ....
       recreated_client = pickle.load(open(fn, "rb"))
       vars(recreated_client)

and then compare the two "vars" results.




More information about the Python-list mailing list