Re: Pickling classes

guido@CNRI.Reston.VA.US
Thu, 20 Apr 95 15:29:52 -0400

>I need to pickle a class instance object that contains a reference to
>another class instance object of a different class imported from a
>different module.
>
>Is this possible using the pickle module? I wasn't sure after reading
>the documentation for the pickle module. It talks about the class
>needing to be defined at the top-level in a module. What exactly does
>this mean?

Yes, this should be no problem. What I meant with the "top-level"
requirement is simply this: the "class" statement that defines the
class must not be contained inside a function. For instance. if I
have the following code:

def spammify(x):
class TempSpam:
def __init__(self, x):
self.x = x
spam = TempSpam(x)
return spam

then the TempSpam instance returned by spammify("Bruce") can't be pickled
because the class TempSpam is invisible from outside the spammify()
function. In general, this coding style is rare (and not really necessary)
so you shouldn't have to worry about it.

--Guido van Rossum <guido@CNRI.Reston.VA.US>
URL: http://www.cwi.nl/~guido/