Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

python - AttributeError when unpickling an object

I'm trying to pickle an instance of a class in one module, and unpickle it in another.

Here's where I pickle:

import cPickle

def pickleObject():
    object = Foo()
    savefile = open('path/to/file', 'w')
    cPickle.dump(object, savefile, cPickle.HIGHEST_PROTOCOL)


class Foo(object):
    (...)

and here's where I try to unpickle:

savefile = open('path/to/file', 'r')
object = cPickle.load(savefile)

On that second line, I get AttributeError: 'module' object has no attribute 'Foo'

Anyone see what I'm doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

class Foo must be importable via the same path in the unpickling environment so that the pickled object can be reinstantiated.

I think your issue is that you define Foo in the module that you are executing as main (__name__ == "__main__"). Pickle will serialize the path (not the class object/definition!!!) to Foo as being in the main module. Foo is not an attribute of the main unpickle script.

In this example, you could redefine class Foo in the unpickling script and it should unpickle just fine. But the intention is really to have a common library that is shared between the two scripts that will be available by the same path. Example: define Foo in foo.py

Simple Example:

$PROJECT_DIR/foo.py

class Foo(object):
    pass

$PROJECT_DIR/picklefoo.py

import cPickle
from foo import Foo

def pickleObject():
    obj = Foo()
    savefile = open('pickle.txt', 'w')
    cPickle.dump(obj, savefile, cPickle.HIGHEST_PROTOCOL)


pickleObject()

$PROJECT_DIR/unpicklefoo.py

import cPickle

savefile = open('pickle.txt', 'r')
obj = cPickle.load(savefile)
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...