泡菜不能泡一个命名元组

时间:2019-02-23 01:02:38

标签: python pickle namedtuple

我正在尝试像这样腌制namedtuple

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不是存储命名元组的最佳方法-哪种方法最有效?

1 个答案:

答案 0 :(得分:3)

您需要在函数外部定义namedtuple,并将namedtuple的名称更改为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)