namespace on python pickle

前端 未结 1 578
梦如初夏
梦如初夏 2021-01-05 08:27

I got an error when I use pickle with unittest.

I wrote 3 program files:

  1. for a class to be pickled,
  2. for a class which use class in #1,
  3. <
相关标签:
1条回答
  • 2021-01-05 08:32

    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'))
    
    0 讨论(0)
提交回复
热议问题