Skip to content Skip to sidebar Skip to footer

Unpickling Objects After Renaming A Module

I have a problem loading objects via numpy.load after renaming a module. Here's a simple example showing the problem. Imagine having a class defined in mymodule.py: class MyClass(o

Solution 1:

NumPy uses pickle for arrays with objects, but adds a header on top of it. Therefore, you'll need to do a bit more than coding a custom Unpickler:

import pickle

from numpy.lib.format import read_magic, _check_version, _read_array_header


class RenamingUnpickler(pickle.Unpickler):
    def find_class(self, module, name):
        if module == 'mymodule':
            module = 'mymodule2'
        return super().find_class(module, name)


with open('dump.npy', 'rb') as fp:
    version = read_magic(fp)
    _check_version(version)
    dtype = _read_array_header(fp, version)[2]
    assert dtype.hasobject
    print(RenamingUnpickler(fp).load())

Post a Comment for "Unpickling Objects After Renaming A Module"