explain this pickle issue to me...

Emile van Sebille emile at fenx.com
Fri Jun 28 13:31:22 CEST 2002


Timothy O'Malley
[snip]
> And the testme.py file used in execfile
> ---------------------------------------
> import cPickle
> class Simple:
>     def __init__(self):
>         self.a = "a"
>         self.b = 2
> # end class A
>
> def writeSimple():
>     s = Simple()
>     return cPickle.dumps(s)
> # end writeSimple
>
> def readSimple(ss):
>     s = cPickle.loads(ss)
>     assert ininstance(s, A), "Not an instance of Simple"
> # end readSimple
>

The problem is that cPickle expects the name of the module holding the
class to be in the pickle, and that execfile doesn't do module
management, but reads it testme.py as __main__, causing the conflict.

If you add to the top of testme:

__name__ = 'testme'
import testme

and change your assert to:

assert isinstance(s, testme.Simple), "Not an instance of Simple"

that should fake it out.  The first makes the creation of pickles use
testme as the module name, and the second and third allows the
isinstance to work.

--

Emile van Sebille
emile at fenx.com

---------




More information about the Python-list mailing list