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

Veek. M vek.m1234 at gmail.com
Wed Mar 9 04:14:36 EST 2016


dieter wrote:

> "Veek. M" <vek.m1234 at gmail.com> writes:
> 
>> import socket
>> class Client(object):
>>  def __init__(self,addr):
>>   self.server_addr = addr
>>   self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>>   self.sock.connect(addr)
>>
>>  def __getstate__(self):
>>   return self.server_addr
>>  
>>  def __setstate__(self,value):
>>   self.server_addr = value
>>   self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>>   self.sock.connect(self.server_addr)
>> -----------------
>>
>> We'd use it like so:
>> x = Client(192.168.0.1)
>> import pickle
>> pickle.dump(x) #getstate gets called and returns IP for pickling.
>>
>> #program exits, we restart it
>> x=Client(None)
>> x = pickle.load(fh) #Is the IP passed to setstate??????
>> x.__setstate__(self, unpickledIP) ???
>> Is this correct?
> 
> Not completely.
> 
> "pickle" operates on objects - and calls "__getstate__" and
> "__setstate__" internally. Thus, you get something like:
> 
>       client = Client()
>       pickle.dump(client, open(fn, "wb"))
>       ....
>       recreated_client = pickle.load(open(fn, "rb"))

hmm.. yeah, as in the fh - file handle will be passed for 
pickling/unpickling - that's not important..

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?

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? 






More information about the Python-list mailing list