Differences between revisions 1 and 2
Revision 1 as of 2008-06-03 08:44:02
Size: 940
Editor: chep03
Comment:
Revision 2 as of 2008-11-15 13:59:44
Size: 940
Editor: localhost
Comment: converted to 1.6 markup
No differences found!

If you are using pickle to store your data and decide to rename some of the modules in your project, you will have troubles loading old saved pickles. However, this can be solved overloading the load_global method in the default pickle implementation like this:

import pickle

try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO

renametable = {
    'old.module': 'new.module',
    'old_name': 'new_name',
    }

def mapname(name):
    if name in renametable:
        return renametable[name]
    return name

def mapped_load_global(self):
    module = mapname(self.readline()[:-1])
    name = mapname(self.readline()[:-1])
    klass = self.find_class(module, name)
    self.append(klass)

def loads(str):
    file = StringIO(str)
    unpickler = pickle.Unpickler(file)
    unpickler.dispatch[pickle.GLOBAL] = mapped_load_global
    return unpickler.load()

UsingPickle/RenamingModules (last edited 2008-11-15 13:59:44 by localhost)

Unable to edit the page? See the FrontPage for instructions.