pythonpickleshelvedbm

How to store an instance object in shelve?


instance1 = class_A()
shelve["key1"] = instance1

So instance1 is a reference to an instance of class_A stored in memory.

Does the above code dereferences the reference instance1 and stores the underlying object instance in shelve? Or does it only store the reference?

Because I don't want to store just the reference instance1 and when the program closes, the underlying object gets released, then the instance1 reference becomes invalid on next program start.


Solution

  • Shelves don't store references to in-memory instances. They serialize objects with pickle and store serialized representations, from which objects can later be recreated. It would be impossible for shelve to do its job if it tried to store references (and trying to store "the underlying object instance" runs into similar problems).