pickling a class definition

Erik Max Francis max at alcyone.com
Tue Apr 22 05:17:10 EDT 2003


Brian Elmegaard wrote:

> I am pickling instances of a class, but in the unpickling script it
> seems that I have to know how the class was defined. I cannot
> pickle the class definition in one script and unpickle in another.
> 
> Is that correct?

When you pickle a class object or instance, you're not really pickling
the whole class definition, you're pickling a reference to the class
name (and instance attributes in the case of an instance, obviously). 
So Python cleverly creates an object and then sets everything up the way
the original one was.

The unpickling process literally tries to access the class the way you
normally would if you were referencing it -- this is what gets pickled. 
So if you pickle it by referencing it one way, and then unpickle it
another way, this is probably where your error is coming from.

So, for instance, say I have a file main.py, and in that file I define a
Widget class, and in main.py I have a pickleAWidget function which
creates a Widget and then pickles it to a file.  Now I have another
script, other.py, which I want to unpickle that pickled Widget.  So I
import main (because that's where Widget is), then try to unpickle the
object but get an error.  That's because in other.py, the Widget class
is main.Widget, not Widget, and so the unpickler can't find it.

So the long and short of it is, when you're pickling and unpickling
objects, make sure that you reference them in the same way on both sides
of the fence.  In this main.py/other.py example, you might make a third
module, util.py, which would contain the actual Widget definition, which
then both main.py and other.py would import (so that to both the class
would be util.Widget) and then they live happily ever after.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ Honesty has nothing to hide
\__/ Joi
    Lsystem / http://www.alcyone.com/pyos/lsystem/
 A Lindenmayer systems explorer in Python.




More information about the Python-list mailing list