[Tutor] Re: Have I run into a limitation of Pickle?

Javier Ruere javier at ruere.com.ar
Tue Feb 8 14:26:45 CET 2005


Johan Kohler wrote:
> Hi,
> In the attached code, I'm trying to pickle and unpickle
> (1) an object containing a list of dictionaries.
> (2) an object containing a list objects each containing a dictionary.
> 
[successful usecase]
> 
> but (2) fails with the following error:
> 
> <__main__.User instance at 0x41a56fac>
> <__main__.User instance at 0x41a56f2c>
> Traceback (most recent call last):
>   File "/usr/lib/python2.3/site-packages/sm/scriptutils.py", line 49,
> in  run
>     exec codeObject in mainDict
>   File "<source>", line 87, in ?
>   File "<source>", line 79, in loadbroken
>   File "<source>", line 33, in readfromfile
>   File "/usr/lib/python2.3/pickle.py", line 1390, in load
>     return Unpickler(file).load()
>   File "/usr/lib/python2.3/pickle.py", line 872, in load
>     dispatch[key](self)
>   File "/usr/lib/python2.3/pickle.py", line 1083, in load_inst
>     klass = self.find_class(module, name)
>   File "/usr/lib/python2.3/pickle.py", line 1140, in find_class
>     klass = getattr(mod, name)
> AttributeError: 'module' object has no attribute 'User'
> Exception raised while running script  <source>
> ---
> 
> I hope this is not a limitation of Pickle, because that would mean I
> have  to change a large section of my code :-(

  Pickle can handle any object but it needs the definition of the class
of the object to be available in order to unpickle.
  For example:

.>>> class A: pass
....
.>>> a = A()
.>>> import pickle
.>>> s = pickle.dumps(a)
.>>> s
'(i__main__\nA\np0\n(dp1\nb.'
.>>> pickle.loads(s)
<__main__.A instance at 0x403fdcec>
.>>> del A
.>>> pickle.loads(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/usr/lib/python2.3/pickle.py", line 1394, in loads
    return Unpickler(file).load()
  File "/usr/lib/python2.3/pickle.py", line 872, in load
    dispatch[key](self)
  File "/usr/lib/python2.3/pickle.py", line 1083, in load_inst
    klass = self.find_class(module, name)
  File "/usr/lib/python2.3/pickle.py", line 1140, in find_class
    klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'A'

  The tracebacks are similar. It seems class User is not available when
unpickling in the second case.

Javier

PS: I have not actually looked at the code so YMMV. :p



More information about the Tutor mailing list