The main reason I use Shelve is to be able to quickly develop code without worrying about db table structure. Unfortunately changing a class name from, say, ‘class1’ to ‘class2’ gives “AttributeError: ‘module’ object has no attribute ‘class2′” on the next run. What is the canonical way to rename a Shelved class? What other similar surprises are lurking deeper into the Shelve db structure?
Shelve uses pickle
to serialize objects. Pickle loads objects by name; the module and class name are stored and looked up when deserialising.
The easiest way to support ‘legacy’ names is to simply create an alias:
class NewName(object):
# a renamed object, once named OldName
# backwards-compatible names for unpickling
OldName = NewName
When unpickling, modulename.OldName
is looked up and used, which is simply the same class as NewName
. When storing a change in the shelve, the new name will be used.
2