If I have a script that defines a class:
script = \"\"\"
class myClass:
def __init__(self):
self.name = \'apple\'
self.color = \'green\'
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)