Python pickling after changing a module's directory

前端 未结 5 1819
生来不讨喜
生来不讨喜 2020-11-30 00:22

I\'ve recently changed my program\'s directory layout: before, I had all my modules inside the \"main\" folder. Now, I\'ve moved them into a directory named after the progra

5条回答
  •  天涯浪人
    2020-11-30 01:03

    This can be done with a custom "unpickler" that uses find_class():

    import io
    import pickle
    
    
    class RenameUnpickler(pickle.Unpickler):
        def find_class(self, module, name):
            renamed_module = module
            if module == "tools":
                renamed_module = "whyteboard.tools"
    
            return super(RenameUnpickler, self).find_class(renamed_module, name)
    
    
    def renamed_load(file_obj):
        return RenameUnpickler(file_obj).load()
    
    
    def renamed_loads(pickled_bytes):
        file_obj = io.BytesIO(pickled_bytes)
        return renamed_load(file_obj)
    

    Then you'd need to use renamed_load() instead of pickle.load() and renamed_loads() instead of pickle.loads().

提交回复
热议问题