Python Save A Class

Let me share a little code snippet I use at times which I call “python save a class”. I came up with a very simple and easy way to do that. Check out my code snippet below.

 

 

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)

    def __str__(self):
        return str(self.__dict__)

The class is saved as whatever the name of the class instance is. Please not that this works with all datatypes that Pickle supports.

Example

myClass = someClass()

Will try to load a saved class called “myClass.txt” otherwise set some sample values and save the class. Feel free to use this code.

Credits

I would also like to give credit to StackOverflow – Getting an instance name inside class init which showed the cool little trick of how to getting the class instance name.

I hope I was able to show you how to save a class in python. Let me know if you have any questions or comments.

The Top 8 WordPress Developer Tools from 5 years experience
(Hint: They cut down my development time in less than half!)

Get the Top Tools Now!

Leave a Reply

Your email address will not be published. Required fields are marked *