首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Pickle functools包装器错误:无法pickle functools.KeyWrapper对象

Pickle functools包装器错误:无法pickle functools.KeyWrapper对象
EN

Stack Overflow用户
提问于 2017-12-27 08:28:48
回答 1查看 294关注 0票数 1

我正在尝试使用SortedListWithKey工具中的cmp_to_key()函数来将比较函数转换为键函数。但是,cmp_to_key()似乎使我的对象不可拾取,并且我得到以下错误: TypeError: can't pickle functools.KeyWrapper objects

我怎么才能修复它?这是一个重现错误的代码示例:

代码语言:javascript
复制
import pickle
from functools import cmp_to_key
from sortedcontainers import SortedListWithKey

def order_fun(a, b):
    if abs(a[0]-b[0]) < 1e-8:
        return 0
    elif a[0]-b[0] > 0:
        return 1
    else:
        return -1

pickle.loads(pickle.dumps(SortedListWithKey([[1,2], [3,4]], key=cmp_to_key(order_fun))))

谢谢!

注意:酸洗在不使用cmp_to_key()函数的情况下工作得很好,但我需要它,因为我的函数不是键函数。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-27 09:43:29

问题似乎是cmp_tp_keynow written in C,并且它返回的类既不是可拾取的,也不是可子类的。然而,最初的纯python版本是still maintained in the source,并且非常简单。当它与您的示例一起使用时,它可以正确地工作。当然,明显的缺点是纯python版本比较慢--但是the difference is not huge

以下是您的示例的工作版本:

代码语言:javascript
复制
import pickle
from sortedcontainers import SortedListWithKey

def order_fun(a, b):
    if abs(a[0]-b[0]) < 1e-8:
        return 0
    elif a[0]-b[0] > 0:
        return 1
    else:
        return -1

class KeyFunc(object):
    __slots__ = ['obj']
    def __init__(self, obj):
        self.obj = obj
    def __lt__(self, other):
        return order_fun(self.obj, other.obj) < 0
    def __gt__(self, other):
        return order_fun(self.obj, other.obj) > 0
    def __eq__(self, other):
        return order_fun(self.obj, other.obj) == 0
    def __le__(self, other):
        return order_fun(self.obj, other.obj) <= 0
    def __ge__(self, other):
        return order_fun(self.obj, other.obj) >= 0
    __hash__ = None

sl = SortedListWithKey([[1,2], [3,4]], key=KeyFunc)

print(sl)

print(pickle.loads(pickle.dumps(sl)))

输出:

代码语言:javascript
复制
SortedListWithKey([[1, 2], [3, 4]], key=<class '__main__.KeyFunc'>)
SortedListWithKey([[1, 2], [3, 4]], key=<class '__main__.KeyFunc'>)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47985058

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档