I'm the dill
author. I'm not sure why you say dill
can't help you.
First if we try to serialize your class, it works:
>>> def func():
... class MyClass():
... pass
... return MyClass
...
>>> import dill
>>> c = func()
>>> c
<class '__main__.func.<locals>.MyClass'>
>>>
>>> dill.dumps(c)
b'\x80\x03cdill._dill\n_create_type\nq\x00(cdill._dill\n_load_type\nq\x01X\x04\x00\x00\x00typeq\x02\x85q\x03Rq\x04X\x07\x00\x00\x00MyClassq\x05h\x01X\x06\x00\x00\x00objectq\x06\x85q\x07Rq\x08\x85q\t}q\n(X\n\x00\x00\x00__module__q\x0bX\x08\x00\x00\x00__main__q\x0cX\x07\x00\x00\x00__doc__q\rNutq\x0eRq\x0f.'
>>> c_ = dill.loads(_)
>>> c_
<class '__main__.MyClass'>
>>>
So, since we know the class serializes, we can then fetch it from your module... although here's the thing... if you try to serialize anything defined in a module that isn't installed (i.e. from just a script you import from the current directory), then it should fail due to the serializer's inability to find the locally defined module (unless it's in __main__
). It's the module that's an issue... if you are opposed for whatever reason to installing the module... then you have to resort to a lesser-known feature of dill
, which is to grab source code from an object. As seen below, you can then either grab the class and define it locally, or you can grab the function and define it locally. Then it will serialize:
>>> import dill
>>> import script1
>>> exec(dill.source.getsource(script1.func(), lstrip=True))
>>> MyClass
<class '__main__.MyClass'>
>>> # or...
>>> exec(dill.source.getsource(script1.func))
>>> c = func()
>>>
>>> dill.dumps(c)
b'\x80\x03cdill._dill\n_create_type\nq\x00(cdill._dill\n_load_type\nq\x01X\x04\x00\x00\x00typeq\x02\x85q\x03Rq\x04X\x07\x00\x00\x00MyClassq\x05h\x01X\x06\x00\x00\x00objectq\x06\x85q\x07Rq\x08\x85q\t}q\n(X\n\x00\x00\x00__module__q\x0bX\x08\x00\x00\x00__main__q\x0cX\x07\x00\x00\x00__doc__q\rNutq\x0eRq\x0f.'
>>> dill.loads(_)
<class '__main__.MyClass'>
>>>
The thing to do is not to try to serialize from a module that is not installed. Either install the module you will import from, or put the function that generates the class inside the same file as the script that is dumping the class.