【问题标题】:python: pickle can't to store local function (Can't pickle local object)python:pickle 不能存储本地函数(Can't pickle local object)
【发布时间】:2020-01-24 18:54:07
【问题描述】:

在我的类方法中,我使用 count 生成唯一 ID,我希望将其存储在类中:

from collections import Counter, defaultdict
import pickle

class A:
   def __init__(self):
      self.models = {}

   def func1(self, data, names):
      ll = []
      for n, seq_list in enumerate(data):
          __counter = count(start=0)

          def _genid():
             return next(__counter)

          __ids = defaultdict(_genid)

          # Here we process seq_list and fill __ids
          # ...

          self.models[name] = [None, None, None, __ids]

   def save_models(self, obj, filename="models.bin"):
        try:
            with open(filename, 'wb') as f:
                pickle.dump(obj, f)
        except IOError as e:
            raise Exception("Failed to open file for writing: %s" % e)

...

data = [['A', 'BB', 'B', 'B', 'B'],
        [['C', 'D', 'E', 'B'], ['E', 'B'], ['C', 'D', 'E', 'B', 'B', 'F']],
        ['A', 'G'],
        [['AA', 'C', 'B', 'B'], ['F', 'D'], ['BB', 'E', 'E', 'F', 'B', 'A']]]
names = ['name1', 'name2', 'name3', 'name4'    

aclass = A()
aclass.func1(data, names)
aclass.save_models(aclass)

此时save_models() 产生错误:AttributeError: Can't pickle local object 'A.func1.._genid'

所以我有两个问题: - 有没有办法让pickle 保存我的课程? - 如果没有,是否有更简单的方法将ids 存储在类中并能够腌制它?

【问题讨论】:

    标签: python-3.x class dictionary


    【解决方案1】:

    选项 1:避免使用 _genid 并使用简单的整数变量进行计数,因为 pickle 模块不支持本地函数。

    选项 2:使用dill 进行酸洗(将import pickle 替换为import dill as pickle)

    参考:Can Python pickle lambda functions?

    【讨论】:

      【解决方案2】:

      该类不能按原样腌制,但可以轻松更改以使其可腌制。直接使用__counter.__next__ 代替_genid 本地包装器:

      __ids = defaultdict(__counter.__next__)
      

      所有defaultdict、count 及其__next__ 方法都可以腌制,从而也允许腌制生成的对象。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-11
        • 2021-08-21
        • 2022-11-12
        • 2021-09-07
        • 2010-11-27
        • 1970-01-01
        • 2017-01-02
        • 1970-01-01
        相关资源
        最近更新 更多