Search code examples
pythonpython-3.xshelve

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']

Solution

  • You can't store classes by pickling and unpickling them like that. When pickle needs to pickle a class, it just records the class's module and name, not the contents. The pickle can only be unpickled in an environment where the same module has the same class defined.