问题描述
我正在学习如何使用泡菜.我创建了一个namedtuple对象,并将其附加到列表中,并尝试使该列表腌制.但是,出现以下错误:
I'm learning how to use pickle. I've created a namedtuple object, appended it to a list, and tried to pickle that list. However, I get the following error:
pickle.PicklingError: Can't pickle <class '__main__.P'>: it's not found as __main__.P
我发现,如果我在运行代码时未将其包装在函数中,则它可以完美运行.当包裹在函数中时,是否需要额外的步骤来腌制一个对象?
I found that if I ran the code without wrapping it inside a function, it works perfectly. Is there an extra step required to pickle an object when wrapped inside a function?
这是我的代码:
from collections import namedtuple
import pickle
def pickle_test():
P = namedtuple("P", "one two three four")
my_list = []
abe = P("abraham", "lincoln", "vampire", "hunter")
my_list.append(abe)
f = open('abe.pickle', 'w')
pickle.dump(abe, f)
f.close()
pickle_test()
推荐答案
创建函数的命名元组外部:
from collections import namedtuple
import pickle
P = namedtuple("P", "one two three four")
def pickle_test():
my_list = []
abe = P("abraham", "lincoln", "vampire", "hunter")
my_list.append(abe)
f = open('abe.pickle', 'w')
pickle.dump(abe, f)
f.close()
pickle_test()
现在pickle
可以找到它;现在它是一个全局模块.拆线时,所有pickle
模块要做的就是再次定位__main__.P
.在您的版本中,P
是pickle_test()
函数的 local ,并且不是自省的或可导入的.
Now pickle
can find it; it is a module global now. When unpickling, all the pickle
module has to do is locate __main__.P
again. In your version, P
is a local, to the pickle_test()
function, and that is not introspectable or importable.
请记住,namedtuple()
是类工厂,这一点很重要;您给它参数,它返回一个类对象供您创建实例. pickle
仅存储实例中包含的 data ,外加对原始类的字符串引用以再次重建实例.
It is important to remember that namedtuple()
is a class factory; you give it parameters and it returns a class object for you to create instances from. pickle
only stores the data contained in the instances, plus a string reference to the original class to reconstruct the instances again.
这篇关于如何正确腌制一个namedtuple实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!