[Tutor] Saving Objects

Paul McGuire ptmcg at austin.rr.com
Thu Jan 17 14:44:22 CET 2008

My initial tests using pickle and a simple class system (shown below) have
failed. The method shown below fails with a AttributeError: 
'FakeModule' object has no attribute 'Spod', so when I create a an empty
class Spod in the new session, it generates an IndexError:(list index out of

Is there a better way to do this?

I'm assuming that "# New session" marks the beginning of a separate Python
file.  The problem is that the Spod class definition is not included in the
pickle file, so you must import that as well, before loading back the
pickled fish object.  Do this;

1. Put Spod in its own module, let's call it spod.py.  (While you are at it,
have Spod derive from object, so that you get a new-style class.)
2. Create test1.py to pickle a Spod.  Have test1.py import spod, and then
have your code that creates spod.Spod("andy") and pickles it to test.pickle.
3. Create test2.py to unpickle a Spod.  Have test2.py *also* import spod,
and then have the rest of your code that follows "# New session".  Modify
the pickle.load statement to save the result to a variable, and then you can
verify that its name is "andy", type is "Spod", etc.

-- Paul

More information about the Tutor mailing list