python failed to serialize object by calling pickle.dump

102 Views Asked by At

I know that pickle.dump() does not work for paddle.Tensor objects. However, I did the following but pickle.dump still failed:

  1. Define a Python class, A, containing an instance member, x, with type paddle.Tensor

  2. Define a bound method for class A named func

  3. Define a Python class, B, its construct method accepts an typing.Callable argument, and will set this callable object as its member self.func

  4. pickle.dump an instance of class B, which I expected would succeed but actually failed

import paddle
import typing


class A(object):
    def __init__(self):
        self.x = paddle.to_tensor([1, 2, 3])

    def func(self):
        # this bound method will be passed to class B construct method as an argument.
        pass


class B(object):
    def __init__(self, f: typing.Callable):
        self.func = f


# main 
def main():
    a = A()
    b = B(f=a.func)

    # try pickle.dump(b) but failed.
    with open("./dumpfile", "wb") as f:
        # TypeError: can't pickle tensor object.
        pickle.dump(b, f)

Can anyone let me know how to dump object b successfully?

Given 2 classes A and B, and 2 instance a = A() and `b = B(.

I expect I can pass the a.func bound method to the b.__init__ construct method as an argument, in the meantime, even if the a object has an member a.x which is type of paddle.Tensor, but still I can pickle.dump(b) successfully.

0

There are 0 best solutions below