RecursionError: maximum recursion depth exceeded while calling a Python object when using pickle.load()

RecursionError: maximum recursion depth exceeded while calling a Python object when using pickle.load()

首先,我知道关于这个特定错误已经提出了多个问题,但我找不到任何解决它发生在我身上的确切上下文的问题。我也尝试了为其他类似错误提供的解决方案,但没有任何区别。

我正在使用 python 模块 pickle 将对象保存到文件并使用以下代码重新加载它:

with open('test_file.pkl', 'wb') as a: 
    pickle.dump(object1, a, pickle.HIGHEST_PROTOCOL)

这不会引发任何错误,但是当我尝试使用以下代码打开文件时:

with open('test_file.pkl', 'rb') as a:
    object2 = pickle.load(a)

我收到这个错误:

---------------------------------------------------------------------------

RecursionError                            Traceback (most recent call last)
<ipython-input-3-8c5a70d147f7> in <module>()
      1 with open('2test_bolfi_results.pkl', 'rb') as a:
----> 2     results = pickle.load(a)
      3

~/.local/lib/python3.5/site-packages/elfi/methods/results.py in __getattr__(self, item)
     95     def __getattr__(self, item):
     96         """Allow more convenient access to items under self.meta."""
---> 97         if item in self.meta.keys():
     98             return self.meta[item]
     99         else:

... last 1 frames repeated, from the frame below ...

~/.local/lib/python3.5/site-packages/elfi/methods/results.py in __getattr__(self, item)
     95     def __getattr__(self, item):
     96         """Allow more convenient access to items under self.meta."""
---> 97         if item in self.meta.keys():
     98             return self.meta[item]
     99         else:

RecursionError: maximum recursion depth exceeded while calling a Python object

我知道其他人在执行 pickle.dump 时也看到了同样的错误 (Hitting Maximum Recursion Depth Using Pickle / cPickle),我尝试通过执行 sys.setrecursionlimit() 来增加最大递归深度,但这并没有' 工作,我要么得到与上面相同的错误,要么我进一步增加它并且 python 崩溃并显示消息:Segmentation fault (core dumped).

我怀疑问题的根源实际上是当我用 pickle.load() 保存对象时,但我真的不知道如何诊断它。

有什么建议吗?

(我在 windows 10 机器上 运行 python3)

这是从 collections.UserDict 派生的相当小的 class,它执行与您的问题对象相同的技巧。它是一个字典,允许您通过普通的 dict 语法或作为属性访问它的项目。我已经投入了一些 print 调用,所以我们可以看到何时调用了主要方法。

import collections

class AttrDict(collections.UserDict):
    ''' A dictionary that can be accessed via attributes '''
    def __setattr__(self, key, value):
        print('SA', key, value)
        if key == 'data':
            super().__setattr__('data', value)
        else:
            self.data[key] = value

    def __getattr__(self, key):
        print('GA', key)
        if key in self.data:
            return self.data[key]
        else: 
            print('NOKEY')
            raise AttributeError

    def __delattr__(self, key):
        del self.data[key]

# test

keys = 'zero', 'one', 'two', 'three'
data = {k: i for i, k in enumerate(keys)}
d = AttrDict(data)
print(d)
print(d.zero, d.one, d.two, d['three'])

输出

SA data {}
{'zero': 0, 'one': 1, 'two': 2, 'three': 3}
GA zero
GA one
GA two
0 1 2 3

到目前为止,还不错。但是如果我们尝试 pickle 我们的 d 实例,我们会得到 RecursionError 因为 __getattr__ 执行属性访问到键查找的神奇转换。我们可以通过为 class 提供 __getstate____setstate__ 方法来克服这个问题。

import pickle
import collections

class AttrDict(collections.UserDict):
    ''' A dictionary that can be accessed via attributes '''
    def __setattr__(self, key, value):
        print('SA', key, value)
        if key == 'data':
            super().__setattr__('data', value)
        else:
            self.data[key] = value

    def __getattr__(self, key):
        print('GA', key)
        if key in self.data:
            return self.data[key]
        else: 
            print('NOKEY')
            raise AttributeError

    def __delattr__(self, key):
        del self.data[key]

    def __getstate__(self):
        print('GS')
        return self.data

    def __setstate__(self, state):
        print('SS')
        self.data = state

# tests

keys = 'zero', 'one', 'two', 'three'
data = {k: i for i, k in enumerate(keys)}
d = AttrDict(data)
print(d)
print(d.zero, d.one, d.two, d['three'])

print('Pickling')
s = pickle.dumps(d, pickle.HIGHEST_PROTOCOL)
print(s)

print('Unpickling')
obj = pickle.loads(s)
print(obj)

输出

SA data {}
{'zero': 0, 'one': 1, 'two': 2, 'three': 3}
GA zero
GA one
GA two
0 1 2 3
Pickling
GS
b'\x80\x04\x95D\x00\x00\x00\x00\x00\x00\x00\x8c\x08__main__\x94\x8c\x08AttrDict\x94\x93\x94)\x81\x94}\x94(\x8c\x04zero\x94K\x00\x8c\x03one\x94K\x01\x8c\x03two\x94K\x02\x8c\x05three\x94K\x03ub.'
Unpickling
SS
SA data {'zero': 0, 'one': 1, 'two': 2, 'three': 3}
{'zero': 0, 'one': 1, 'two': 2, 'three': 3}

但是我们可以做些什么来修复具有这种行为的现有 class?幸运的是,Python 允许我们轻松地将新方法添加到现有的 class,甚至是我们通过导入获得的方法。

import pickle
import collections

class AttrDict(collections.UserDict):
    ''' A dictionary that can be accessed via attributes '''
    def __setattr__(self, key, value):
        print('SA', key, value)
        if key == 'data':
            super().__setattr__('data', value)
        else:
            self.data[key] = value

    def __getattr__(self, key):
        print('GA', key)
        if key in self.data:
            return self.data[key]
        else: 
            print('NOKEY')
            raise AttributeError

    def __delattr__(self, key):
        del self.data[key]

# Patch the existing AttrDict class with __getstate__ & __setstate__ methods

def getstate(self):
    print('GS')
    return self.data

def setstate(self, state):
    print('SS')
    self.data = state

AttrDict.__getstate__ = getstate
AttrDict.__setstate__ = setstate

# tests

keys = 'zero', 'one', 'two', 'three'
data = {k: i for i, k in enumerate(keys)}
d = AttrDict(data)
print(d)
print(d.zero, d.one, d.two, d['three'])

print('Pickling')
s = pickle.dumps(d, pickle.HIGHEST_PROTOCOL)
print(s)

print('Unpickling')
obj = pickle.loads(s)
print(obj)

这段代码产生的结果与之前的版本相同,这里不再赘述。

希望这能为您提供足够的信息来修复您的故障对象。我的 __getstate____setstate__ 方法 保存和恢复 .data 字典中的内容。为了正确地腌制你的对象,我们可能需要更激烈一些。例如,我们可能需要保存和恢复实例的 .__dict__ 属性,而不仅仅是 .data 属性,它对应于您问题对象中的 .meta 属性。