Search code examples
pythonclassautosave

how to save/read class wholly in Python


som = SOM_CLASS() # includes many big difficult data structures
som.hard_work()
som.save_to_disk(filename)
#then later or another program
som = SOM_CLASS()
som.read_from_file(filename)
som.do_anythink_else()

or

som = SOM_CLASS()
save(som)
#...
load(som)
som.work()

what is easiest way to do this?


Solution

  • You can (de)serialize with pickle. It is backward-compatible, i.e. it will support all old protocols in future versions.

    import pickle
    
    som = SOM_CLASS()
    fileObject = <any file-like object>
    pickle.dump(som, fileObject)
    #...
    som = pickle.load(fileObject)
    som.work()
    

    But mind that if you transfer pickled objects to another computer, make sure the connection cannot be tampered with as pickle might be unsecure (this is an article that every pickle user should know).

    Another alternative is the older module marshal.