Python: can't pickle module objects error

后端 未结 4 1811
不思量自难忘°
不思量自难忘° 2020-12-16 13:24

I\'m trying to pickle a big class and getting

TypeError: can\'t pickle module objects

despite looking around the web, I can\'t e

4条回答
  •  半阙折子戏
    2020-12-16 14:03

    According to the documentation:

    What can be pickled and unpickled?

    The following types can be pickled:

    • None, True, and False

    • integers, floating point numbers, complex numbers

    • strings, bytes, bytearrays

    • tuples, lists, sets, and dictionaries containing only picklable objects

    • functions defined at the top level of a module (using def, not lambda)

    • built-in functions defined at the top level of a module

    • classes that are defined at the top level of a module

    • instances of such classes whose __dict__ or the result of calling __getstate__() is picklable (see section Pickling Class Instances for details).

    As you can see, modules are not part of this list. Note, that this is also true when using deepcopy and not only for the pickle module, as stated in the documentation of deepcopy:

    This module does not copy types like module, method, stack trace, stack frame, file, socket, window, array, or any similar types. It does “copy” functions and classes (shallow and deeply), by returning the original object unchanged; this is compatible with the way these are treated by the pickle module.

    A possible workaround is using the @property decorator instead of an attribute. For example, this should work:

        import numpy as np
        import pickle
    
        class Foo():
            @property
            def module(self):
                return np
    
        foo = Foo()
        with open('test.out', 'wb') as f:
            pickle.dump(foo, f)
    

提交回复
热议问题