getstate, setstate and pickle

Ovidiu Predescu ovidiu at cup.hp.com
Thu Jun 24 19:40:34 EDT 1999


Emile van Sebille wrote:
> 
> I've written a class, instantiated, then pickled the instance.  At
> first, pickling wouldn't work at all, but through some mix of
> eliminating a class variable 'id' and adding __setstate__ and
> __getstate__ methods it does dump (too soon to call it a pickle).
> 
> What I'm having trouble with is getting the load to match the dump.  I
> lifted parts of the pickle module test code, and the dump == load part
> fails, then my code falls apart, and then nothing works... (I'm in
> California, so picking grapes is an option ;-)
> 
> I'm probably not using get/set state properly.  My instance should be
> pickleable or I'd get an error there.
> 
> Any help or pointers to examples/docs appreciated.

You don't need the __setstate__/__getstate__ methods unless you want to
exclude some instance variables from being pickled. On a normal class
the pickling should work without any problem. I also never had problems
with the name of the instance variables.

If you want to compare your own defined classes, don't forget to define
the __cmp__ method. This method defines how to compare instances of the
same class.

Here is a short example on how to pickle some objects:

from cPickle import Pickler, Unpickler
from StringIO import StringIO

class MyClass:
    def __init__ (self, value):
        self.value = value

    def __repr__ (self):
        return '[MyClass: %s]' % (self.value,)

    def __cmp__ (self, other):
        return self.value == other.value

object = MyClass (MyClass (123))
strIO = StringIO ()
pickler = Pickler (strIO)
pickler.dump (object)
strIO.seek (0, 0)
unpickler = Unpickler (strIO)
object2 = unpickler.load ()

print 'object: '+`object`
print 'object2: '+`object`

print object == object2


Hope this helps,
--
Ovidiu Predescu <ovidiu at cup.hp.com>
http://www.geocities.com/SiliconValley/Monitor/7464/




More information about the Python-list mailing list