Search code examples
pythonoopself

How to save all "self" variables in Python after __init__()


I have a class and some self variables inside __init__() function. Some of the self variables are derived and it has mixed data types. How can I save all these self variables so I can debug it whenever errors occur?

Please advise


Solution

  • You can check out pickle: official docs. It works with all data types, even with custom ones (but you still have to have the custom classes defined when you load the data)
    It saves data to one single file. If you know what variables you want to save you can use:

    import pickle
    
    
    class Test:
        def __init__(self, a, b, c):
            self.a = a
            self.b = b
            self.c = c
            pickle.dump([a, b, c], open('dumpfile.pickle', 'wb'))
    
    
    test = Test(1, 2, 3)  # Creates file dumpfile.pickle that contains the pickled list [1, 2, 3]
    # To load the data back, even if in another file:
    loaded_data = pickle.load(open('dumpfile.pickle', 'rb'))  # [1, 2, 3]
    

    Hope it can help you!