首页 > 解决方案 > 如何使 OrderedSet 可腌制?

问题描述

集合的 python 文档链接到OrderedSet数据类型的接收者。这个类的行为像一个集合,但保持插入顺序。

链接(在页面底部): https ://docs.python.org/3/library/collections.abc.html?highlight=orderedset

链接目标: https ://code.activestate.com/recipes/576694/

我现在想让这个类可腌制,但双向链表会导致递归错误。作为解决方案,我在此类中添加了以下方法:

def __getstate__(self):
    """ Avoids max depth RecursionError when dumping with pickle"""
    return list(self)

def __setstate__(self, state):
    """ Tells pickle how to restore instance using state """
    self.__init__(state)

这行得通,但我觉得在__init__里面打电话很奇怪__setstate__。此外,它需要从头开始重建链表。有没有更好的方法让这个类可以腌制?

标签: python-3.xsetpickle

解决方案


正如 Mad Physicist 在评论(如何使 OrderedSet pickleable?)中提到的那样,问题中提出的解决方案是合理的。为 OrderedSet 类定义以下方法为 pickle 提供了它需要存储的信息,然后重构 OrderedSet 的内容:

def __getstate__(self):
    """ Avoids max depth RecursionError when dumping with pickle"""
    return list(self)

def __setstate__(self, state):
    """ Tells pickle how to restore instance using state """
    self.__init__(state)

在内部,pickle 会将 的内容存储OrderedSetlist,然后可以通过使用存储的列表OrderedSet调用 的__init__()方法来重构 。OrderedSet

作为奖励,copy.deepcopy()回退到腌制/取消腌制,copy.deepcopy()现在也可以工作。


推荐阅读