Search code examples
pythonserializationcopyinstancepickle

How do I copy an instance that has non-pickleable objects stored within it?


I have objects within my instance that are not pickleable. However, I would like to be able to save the instance as the program runs in case something happens. This way I can easily restart the program.

My thought was:

  1. Create copy of instance as new_instance
  2. Re-write all non-pickleable objects in new_instance to None
  3. Pickle new_instance
  4. Repeat at a specified time interval

However, copy() and deepcopy() do not work. copy() just assigns the reference to the original object for some reason & Deepcopy() gives me the same error that the objects in my instance aren't pickleable.

Is there another option / better method that I should be using? Is there a way to ignore certain object types when pickling so I don't need to create a copy, rewrite, and pickle?


Solution

  • I ended up writing the logic myself based on juanpa.arrivillaga's input.

    I created an empty copy within the init(self) of the class. Then, later updated using a function like below:

    def save_copy(self):
         for i, j in self.__dict__.items():
              # Ignore nonpickeable items
              if(type(i) == 'nonpickeable'):
                  pass
              else:
                  # Set copy dictionary to instance dictionary
                  # if pickeable
                  self._copy.__dict__[i] = j