Save and load initialized class

dieter dieter at handshake.de
Sat Dec 9 03:38:25 EST 2017


Bob van der Poel <bob at mellowood.ca> writes:

> 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"
> ....
> 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?

You could use:

  for k, v in z.iteritems: setattr(Opts, k, v)


Of course, this means that you already have a class "Opts" (maybe
without or with different parameter values).


This poses the question why you want to dump/load the class in the first
place. Usually, you would want to have the values in code, not stored/loaded.


If you really want make parameter values persistent, you could use
the following approach:

class ParameterCollection(object):
  def __init__(self, **kwargs):
    for k, v in kwargs.iteritems(): setattr(self, k, v)

my_parameters = ParameterCollection(a=1, b=2, )

from pickle import load, dump
dump(my_parameters, open(..., "wb"), -1)
...
my_parameters_reloaded = load(open(..., "rb"))




More information about the Python-list mailing list