Why can't I pickle this object?

后端 未结 3 1974
野的像风
野的像风 2020-12-14 10:13

I have a class (below):

class InstrumentChange(object):
    \'\'\'This class acts as the DTO object to send instrument change information from the
       cl         


        
相关标签:
3条回答
  • 2020-12-14 10:58

    It is failing because it can't find __getstate__() for your object. Pickle needs these to determine how to pickle/unpickle the object. You just need the __getstate__() and __setstate__() methods.

    See the TextReader example in the docs: http://docs.python.org/library/pickle.html

    Update: I just looked at the sourceforge page for the Mock module, and I think you are also using it incorrectly. You are mocking a file-object, but when pickle tries to read from it, it won't get anything back which is why getattr() returns none.

    0 讨论(0)
  • 2020-12-14 11:01

    Your code has several minor "side" issues: the sudden appearance of a 'Transport' in the class name used in the test (it's not the class name that you're defining), the dubious trampling over built-in identifier file as a local variable (don't do that -- it doesn't hurt here, but the habit of trampling over built-in identifiers will cause mysterious bugs one day), the misuses of Mock that has already been noted, the default use of the slowest, grungiest pickling protocol and text rather than binary for the pickle file.

    However, at the heart, as @coonj says, is the lack of state control. A "normal" class doesn't need it (because self.__dict__ gets pickled and unpickled by default in classes missing state control and without other peculiarities) -- but since you're overriding __getattr__ that doesn't apply to your class. You just need two more very simple methods:

    def __getstate__(self): return self.__dict__
    def __setstate__(self, d): self.__dict__.update(d)
    

    which basically tell pickle to treat your class just like a normal one, taking self.__dict__ as representing the whole of the instance state, despite the existence of the __getattr__.

    0 讨论(0)
  • 2020-12-14 11:01
        file = open('testpickle.dat', 'w')
        file = Mock()
    

    You are losing here reference to the opened file. Might that be a problem?

    0 讨论(0)
提交回复
热议问题