How to pickle functions/classes defined in __main__ (python)

前端 未结 3 1290
清酒与你
清酒与你 2021-01-18 14:08

I would like to be able to pickle a function or class from within __main__, with the obvious problem (mentioned in other posts) that the pickled function/class is in the __m

3条回答
  •  梦毁少年i
    2021-01-18 14:37

    If you are trying to pickle something so that you can use it somewhere else, separate from test_script, that's not going to work, because pickle (apparently) just tries to load the function from the module. Here's an example:

    test_script.py

    def my_awesome_function(x, y, z):
        return x + y + z
    

    picklescript.py

    import pickle
    import test_script
    with open("awesome.pickle", "wb") as f:
        pickle.dump(test_script.my_awesome_function, f)
    

    If you run python picklescript.py, then change the filename of test_script, when you try to load the function, it will fail. e.g.

    Running this:

    import pickle
    with open("awesome.pickle", "rb") as f:
        pickle.load(f)
    

    Will give you the following traceback:

    Traceback (most recent call last):
      File "load_pickle.py", line 3, in 
        pickle.load(f)
      File "/Library/Frameworks/Python.framework/Versions/7.3/lib/python2.7/pickle.py", line 1378, in load
        return Unpickler(file).load()
      File "/Library/Frameworks/Python.framework/Versions/7.3/lib/python2.7/pickle.py", line 858, in load
        dispatch[key](self)
      File "/Library/Frameworks/Python.framework/Versions/7.3/lib/python2.7/pickle.py", line 1090, in load_global
        klass = self.find_class(module, name)
      File "/Library/Frameworks/Python.framework/Versions/7.3/lib/python2.7/pickle.py", line 1124, in find_class
        __import__(module)
    ImportError: No module named test_script
    

提交回复
热议问题