explain this pickle issue to me...

Timothy O'Malley timo at alum.mit.edu
Fri Jun 28 00:09:52 EDT 2002


hola.

Can someone explain why I can't seem to use Pickle (actually
cPickle) in combination with execfile?

Sample code:
-----------------------------------
Python 2.2.1 (#1, 06/20/02, 11:40:06) 
[GCC Apple devkit-based CPP 6.0] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {}
>>> execfile("testme.py", d)
>>> q = d["writeSimple"]()
>>> print `q`
"(i__builtin__\nSimple\np1\n(dp2\nS'a'\nS'a'\nsS'b'\nI2\nsb."
>>> d["readSimple"](q)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "testme.py", line 14, in readSimple
    s = cPickle.loads(ss)
AttributeError: 'module' object has no attribute 'Simple'
>>> d["readSimple"].func_globals.keys()
['__builtins__', 'Simple', 'cPickle', 'readSimple', 'writeSimple']


And the testme.py file used in execfile
---------------------------------------
import cPickle
class Simple:
    def __init__(self):
        self.a = "a"
        self.b = 2
# end class A

def writeSimple():
    s = Simple()
    return cPickle.dumps(s)
# end writeSimple

def readSimple(ss):
    s = cPickle.loads(ss)
    assert ininstance(s, A), "Not an instance of Simple"
# end readSimple


---------------


As I understand it from the docs, there is a restriction in
Pickle that requires class definitions to be in the global
namespace in order to be found.  And, it appears, I am running
afoul of that restriction.

But -- the last two lines of the posted sample code shows
that the class definition *is* in the global namespace of
the readSimple function.

What's the catch?

TimO



More information about the Python-list mailing list