0

I am writing a program that should run more or less continously. If I terminate the program, or if it throws an error, I want all object instances to be saved. To do so, I save all instances using jsonpickle. When the program continues, I want to continue exactly where I left off. My idea was to do something like the following:

class A(object):
    def __init__(self):
       try:
            with open('A.json', 'r') as fp:
                 self = jsonpickle.decode(json.load(fp))
       except IOError:
            self.X = 'defaultvalue'
            self.Y = 'defaultvalue'

Where A.json contains an instance of A previously saved using jsonpickle (that part works). However, self is not overwritten by my code.

I suspect that I have to implement what I want to do in __new__. I read the documentation, however I am a bit lost. I would appreciate any advice on how to implement what I want in a good way.

Tobias
  • 514
  • 6
  • 17

1 Answers1

0

I dont know about jsonpicle, but with JSON you could do something like this:

import json

class ClassA(object):
    def __init__(self):
       try:
            with open('A.json', 'r') as fp:
                 self.__dict__ = json.loads(fp.read())
       except IOError:
            self.X = 'defaultvalue'
            self.Y = 1

    def __del__(self):
       with open('A.json', 'wb') as fp:
          fp.write( json.dumps( self.__dict__) )

if __name__ == "__main__":       
   myobj  = ClassA()
   print "GOT X : " + str(myobj.X)
   print "GOT Y : " + str(myobj.Y)
   myobj.X += " RUN ME AGAIN "
   myobj.Y += 1
   myobj = None

Do note that the __del__ is called by garbage collector; at least to me it failed utterly if i did not have the myobj = None there.

Anyway you are going to end up in troubles if you just assume you can always write the stuff on disk on shutdown; think what happens when you pull out the power plug: i suggest doing writes as soon as possible (and call some flushing function to make sure the modifications do get written to disk also).

susundberg
  • 650
  • 7
  • 14