首页 > 解决方案 > KeyError and AtrributeError when trying to retrieve a shelved class - Python 3.6

问题描述

When serializing a class in one program(with shelve), I cannot retrieve it without getting the follow error:

 File "\Python36_64\lib\shelve.py", line 111, in __getitem__
    value = self.cache[key]
KeyError: 'foo'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "program.py", line 12, in <module>
    bar = db['foo']
  File "\Python36_64\lib\shelve.py", line 114, in __getitem__
    value = Unpickler(f).load()
AttributeError: Can't get attribute 'bar' on <module '__main__' (built-in)>

This is my code initializing the shelf. It compiled:

import shelve 
class bar:
   x = {}
db = shelve.open('file.dat')
db['foo'] = bar

I've been trying to retrieve class bar in another program with the following code. This has not compiled properly.:

import shelve
db = shelve.open('file.dat')
bar = db['foo']

标签: pythonpython-3.xshelve

解决方案


你不能像这样腌制和解开它们来存储类。当pickle需要pickle一个类时,它只记录类的模块和名称,而不是内容。只有在相同模块定义了相同类的环境中才能取消腌制。


推荐阅读