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 perfect season to determination soundness problem is before any visible sign appears. Actually there isn’t anything you can’t purchase on the Internet anymore. Whereas erectile disfunction is more common among older men, that doesn’t something you just have to live with. What about “canadian pharmacy cialis 5 mg” and “cialis canadian pharmacy“? In our generation, there are divers options for those ones who suffer from erectile disfunction. You may have heard about “canadian pharmacy online cialis“. More information about the question available at “canadian pharmacy cialis 20mg“. Why it happen? Can sexual disorders in men be prevented? If you get any prescription remedies like Viagra, check with a dispenser that they are sure to take with your other remedies.