0

I'm trying to save the state of my program using pickle, so that I can jump to different states with objects created on a different run.

The issue is that virtually all of these objects (there are quite a few) all have logger objects, so they are all modifying files, and this screws pickling up.

Is there any way to just close all currently open file, so that I can just pickle them?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
H X
  • 43
  • 1
  • 7
  • When you unpickle to "jump" to a state, what state do you expect or want the loggers to be in? – martineau Aug 22 '14 at 19:55
  • If your issue is that the logger instances don't serialize with pickle... maybe you could use a better pickler? I know that the `dill` pickler can serialize logger instances. – Mike McKerns Aug 22 '14 at 20:45

1 Answers1

2

You can limit what is pickled by including a __getstate__ method:

def __getstate__(self):
    state = vars(self).copy()
    del state['logger']  # remove logger object
    return state

You may need to include a __setstate__ as well in that case, to recreate the logger object.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • All ready tried this. Issue is that logger is also present implicitly in many objects. – H X Aug 22 '14 at 18:46
  • @HX: it cannot be present implicitly; it may be present *inside other attributes* though, like in a list or dictionary. It is still up to your application code to either not reference these on instances or to produce a state that doesn't include them. – Martijn Pieters Aug 22 '14 at 18:48