Problem pickling class instance

David Bolen db3l at fitlinxx.com
Fri Jun 7 00:53:39 EDT 2002


"Edward C. Jones" <edcjones at erols.com> writes:

> First I run mod.py then top.py. The latter give the message:
> 
>      AttributeError: 'module' object has no attribute 'A'
> 
> Please explain the problem to me. Is there a standard work-around?

Pickle only pickles object instance data, not the code representing
the object (class) itself.  Instead it includes a reference to the
name of the class which the object data represents.

When you pickled your instance of class A, that's the name used in the
resulting pickle.  It tries to instantiate a new instance of that
object class when de-pickling in order to populate that instance with
the instance data from the pickle.

But when you try to load it, you've imported the mod module, so that
same class is now known in your namespace as "mod.A", and thus pickle
can't find the normal "A" class it expects for the data it is
de-pickling.

In this specific case, you could either:

  * Do a "from mod import A" (whether or not you're importing mod itself)
  * After doing an "import mod" somewhere before the pickle do "A=mod.A"

Both of these will add a local module-level binding for the name "A"
to the actual class in the module "mod".  Note that you need to have
these statements at module level since pickle expects to find the
class definition at that level.

Whether or not that's an appropriate overall solution depends on the
problem.  If a class is something that is going to be used in a pickle
that is common between two parts of the system, it probably makes
sense to isolate it to its own module (or package), and have all users
of it be in a separate module and import that module to access the
class.  Either that or include the pickling/de-pickling operations
both within the same module as the class so they are always local.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list