本文介绍了Pickle 不能pickle 一个namedtuple的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试像这样腌制 namedtuple
:
I am trying to pickle the namedtuple
like this:
def f():
TemplateData = namedtuple('TemplateData', ['field1', 'field2'])
f1 = np.random.randn(50,50)
f2 = np.random.randn(50,50)
td = TemplateData(f1, f2)
return td
data = f()
with open("aaaa.pkl", "wb") as fl:
pkl.dump(data, fl)
但由于错误而崩溃:
PicklingError: Can't pickle <class '__main__.TemplateData'>: it's not the same object as __main__.TemplateData
怎么了?如果 pickle
不是存储命名元组的最佳方式 - 最有效的方式是什么?
What's wrong?If pickle
is not the best way to store named tuple - what is the most efficient way?
推荐答案
你需要在你的函数之外定义namedtuple,并将namedtuple的名字改成TemplateData
.
You need to define the namedtuple outside of your function, and change the name of your namedtuple to TemplateData
.
TemplateData = namedtuple('TemplateData', ['field1', 'field2'])
f1 = np.random.randn(50,50)
f2 = np.random.randn(50,50)
model_cluster = TemplateData(f1, f2)
with open("aaaa.pkl", "wb") as fl:
pkl.dump(model_clusters_dict, fl)
这篇关于Pickle 不能pickle 一个namedtuple的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!