How to unpickle an object whose class exists in a different namespace (python)?

前端 未结 2 1918
清酒与你
清酒与你 2021-01-04 07:26

If I have a script that defines a class:

script = \"\"\"

class myClass:
    def __init__(self):
        self.name = \'apple\'
        self.color = \'green\'         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-04 07:31

    I discovered a solution this. It seems the problem is executing code in a dict prevents python from figuring out where the class is defined. The solution is to create an empty module, execute the code in the module, and then add the module to sys.modules so python knows about it.

    script = """
    class myClass:
        def __init__(self):
            self.name = 'apple'
            self.color = 'green'
    """
    
    import imp, sys
    
    moduleName = 'custom'
    
    module = imp.new_module(moduleName)
    
    exec script in module.__dict__
    
    sys.modules[moduleName] = module
    

    Now it is possible to pickle and unpickle an instance of the class:

    import pickle
    a = module.myClass()
    s = pickle.dumps(a)
    b = pickle.loads(s)
    

提交回复
热议问题