Save and load initialized class

MRAB python at mrabarnett.plus.com
Sat Dec 9 12:52:44 EST 2017


On 2017-12-08 18:36, Bob van der Poel wrote:
> I'm trying to something simple (yeah, right). Mainly I want to have a bunch
> of variables which my program needs and uses to be in a saveable/loadable
> block. Currently I have then all as a bunch of globals which works, but
> trying to keep track of them and the correct spellings, etc becomes a bit
> of maintenance nightmare. So, demonstrating all my cleverness I came up
> with:
> 
> class Opts():
>       var1 = 123
>       var2 = "hello world"
> 
> Notationally, it looks much like the variables are stored in a separate
> module. I can call these options from within a function with the simple
> notation:
> 
>        if Opts.var1 == 99 ...
> 
> And, if I need to change a value I can:
> 
>       global
>       Opts.var1 = 0
> 
> Further, and importantly, I can save the lot with:
> 
>    json.dump(Opts.__dict__, open("mybuffer", "w"))
> 
> But, I can't figure out how to load the saved data back into my program.
> Doing
> 
>    z=json.load (open("mybuffer", "r"))
> 
> loads a dictionary ... which makes sense since that is what I saved. So,
> can I now reset the values in Opts from a saved dictionary?
> 
Try updating __dict__:

     Opts.__dict__.update(json.load(open("mybuffer")))



More information about the Python-list mailing list