Search code examples
pythonmultiple-inheritance

How to pass a class variable from the first execution of the program to the next execution?


I am trying to contribute to a Python project which consists of multiple classes and multiple inheritance. My goal is to use a class variable from previous execution of the program as an input to the next execution.

Since the next execution of the program will use different parameters, I need to store this variable and pass to the next program. The variable is dictionary of objects and its values.

I don't have enough experience to decide on the optimal approach, but those ideas what I have right now:

  • Objects are all the same type, so maybe instead of storing the dictionary as a variable I can create a different class to store the information.
  • Create a test class and execute the first program. Return the dictionary, and pass it to the next execution.
  • Save the dictionary to a file and use it in the next execution.

Codebase is quite complex for me as a beginner, so what I would like to ask is any of my ideas are better than the other or is there anything else I can think of?


Solution

  • I think this article might help greatly.

    https://pythonprogramming.net/python-pickle-module-save-objects-serialization/

    Here is how you would save a dict and reopen it the next time the program is run. As far as I am familiar, this should work for any data type.

    #Saving dict
    import pickle
    example_dict = {1:"6",2:"2",3:"f"}
    
    pickle_out = open("dict.pickle","wb")
    pickle.dump(example_dict, pickle_out)
    pickle_out.close()
    
    
    #Reopening dict
    pickle_in = open("dict.pickle","rb")
    example_dict = pickle.load(pickle_in)