TypeError: can't pickle weakref objects

Viewed 3338

I am trying to pickle.dump() an object with a model property that stores a TensorFlow model.
This is the minimum code to reproduce my error (at least on my machine, macOS Big Sur 11.4 with Anaconda Python 3.6 enviroment and TensorFlow 2.3.1).

import tensorflow as tf
import pickle as pkl

class OBJ():
    def __init__(self):
        self.model = tf.keras.models.Sequential()

save_location = 'your save location here'
pkl.dump(OBJ(), save_location)

On run time this exception is thrown

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't pickle weakref objects

Reading online forums I realised that this error has something to do with the fact that there are some objects (like TensorFlow models) that cannot be pickled.
Does anybody know a method to pickle an "unpickable" object? What makes these object specials, so that they can't be pickled?

0 Answers
Related