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

Ian Kelly ian.g.kelly at gmail.com
Wed Mar 9 16:28:46 EST 2016


On Wed, Mar 9, 2016 at 2:14 AM, Veek. M <vek.m1234 at gmail.com> wrote:
> 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?

pickle doesn't care what the return value is, other than it needs to
be something picklable. I suggest returning a dict containing the IP
address, to make it easier to add additional state later if needed.

That said, I wouldn't pickle a TCP client in the first place. You may
be able to restore the client state, but you can't easily restore any
server state, which could easily lead to mismatching network states.
Also, what do you think should happen if the connection fails while
unpickling?

> Similarly, whilst unpickling, __setstate__ will be called in a manner
> similar to this:
> x.__setstate__(self, unpickledIP)
>
> __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?

Correct.



More information about the Python-list mailing list