如何找到有问题的(不可腌制的)对象?

How to locate problematic (un-picklable) object?

尝试 pickle 对象时,我收到以下错误消息:

TypeError: cannot serialize '_io.TextIOWrapper' object

有问题的对象 class 继承了另一个 class (pytorch_lightning.LightningModule),所以我假设有问题的对象属于超级 class。我怎样才能找到它?错误跟踪只会导致我的 pickling 命令,即

with open(save_path, "wb") as p:
    pickle.dump(self, p)

根据pickle documentation you can influence on how an object is pickled by defining __getstate__函数。

Classes can further influence how their instances are pickled; if the class defines the method __getstate__(), it is called and the returned object is pickled as the contents for the instance, instead of the contents of the instance’s dictionary. If the __getstate__() method is absent, the instance’s __dict__ is pickled as usual.

尝试执行以下操作:

def __getstate__(self):
    for variable_name, value in vars(self).items():
        try:
            pickle.dumps(value)
        expect:
            print('{variable_name} with value {value} is not pickable')

当您尝试 pickle 对象时,它应该打印出对象的 un-picklable 对象。

替代方式:

If the __getstate__() method is absent, the instance’s __dict__ is pickled as usual.

以相同的方式检查对象 __dict__,尝试对每个变量进行 pickle 以找出有问题的变量。