Unpickling python objects with a changed module path

后端 未结 4 1743
梦如初夏
梦如初夏 2020-12-14 02:29

I\'m trying to integrate a project Project A built by a colleague into another python project. Now this colleague has not used relative imports in his code but

4条回答
  •  抹茶落季
    2020-12-14 02:52

    You'll need to create an alias for the pickle import to work; the following to the __init__.py file of the WrapperPackage package:

    from .packageA import * # Ensures that all the modules have been loaded in their new locations *first*.
    from . import packageA  # imports WrapperPackage/packageA
    import sys
    sys.modules['packageA'] = packageA  # creates a packageA entry in sys.modules
    

    It may be that you'll need to create additional entries though:

    sys.modules['packageA.moduleA'] = moduleA
    # etc.
    

    Now cPickle will find packageA.moduleA and packageA.moduleB again at their old locations.

    You may want to re-write the pickle file afterwards, the new module location will be used at that time. The additional aliases created above should ensure that the modules in question have the new location name for cPickle to pick up when writing the classes again.

提交回复
热议问题