I got an error when I use pickle with unittest.
I wrote 3 program files:
That because __main__.ClassToPickle != ClassToPickle.ClassToPickle
, think of it like this:
When you pickled the class instance of ClassToPickle in the ClassToPickle.py
script, the pickle module will pickle all the reference to the class which mean it will pickle the module name where the class was defined, and because you executed the script ClassToPickle.py
this mean that the module will be set to __main__
which mean that pickle
module will pickle __main__.ClassToPickle
.
And when you tried to load the pickled instance it fail because it didn't find the instance's class which is __main__.ClassToPickle
and not the one that you imported using from ClassToPickle import ClassToPickle
because this latest is ClassToPickle.ClassToPickle
.
A fix will be to create another script that will handle dumping instead of doing it in ClassToPickle.py
e.g.
import pickle
from ClassToPickle import ClassToPickle
if __name__=="__main__":
p = ClassToPickle(10)
pickle.dump(p, open('10.pickle', 'w'))