27
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?

Mike
  • 1,008
  • 3
  • 12
  • 15

4 Answers4

31

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.

AndiDog
  • 68,631
  • 21
  • 159
  • 205
14

I use this code:

import cPickle
import traceback

class someClass():
    def __init__(self):
        #set name from variable name. http://stackoverflow.com/questions/1690400/getting-an-instance-name-inside-class-init
        (filename,line_number,function_name,text)=traceback.extract_stack()[-2]
        def_name = text[:text.find('=')].strip()
        self.name = def_name

        try:
            self.load()
        except:
            ##############
            #to demonstrate
            self.someAttribute = 'bla'
            self.someAttribute2 = ['more']
            ##############

            self.save()

    def save(self):
        """save class as self.name.txt"""
        file = open(self.name+'.txt','w')
        file.write(cPickle.dumps(self.__dict__))
        file.close()

    def load(self):
        """try load self.name.txt"""
        file = open(self.name+'.txt','r')
        dataPickle = file.read()
        file.close()

        self.__dict__ = cPickle.loads(dataPickle)

This code saves and loads the class from its actual class instance name. Code is from my blog http://www.schurpf.com/python-save-a-class/.

schurpf
  • 609
  • 7
  • 7
2

Take a look at Python's pickle library.

Amber
  • 507,862
  • 82
  • 626
  • 550
1

Use pickle in this way:

import pickle
class Student:
    def __init__(self, name, age, grade):
        self.name = name
        self.age = age
        self.grade = grade # 0 - 100
    def get_grade(self):
        print (self.grade)
s1 = Student("Tim", 19, 95)

#save it
with open(f'test.pickle', 'wb') as file:
    pickle.dump(s1, file) 

#load it
with open(f'test.pickle', 'rb') as file2:
    s1_new = pickle.load(file2)

#check it
s1_new.get_grade()
# it prints 95
Hadij
  • 3,661
  • 5
  • 26
  • 48