Class Persistence using __dict__

Gene C gchiaramonte at
Mon Sep 4 15:55:27 CEST 2000

I want to add simple persistence to some of my python classes using cPickle.
I have seen where others have stored all the class data in a dictionary
( = {}) then dump and load the dictionary from within the class. I
want something more robust that will also save and load any new class data I
might add to the class on the fly. The following seems to work fine. I was
wondering if some python experts might have any comments/suggestions.
Thanks. Gene

class Test:
    def __init__(self): = 1 = "Test Class"
        self.my_list = [1,2,3]

    def Save(self, fn):
        f = open(fn, "w")
        cPickle.dump(self.__dict__, f)

    def Load(self, fn):
        f = open(fn, "r")
        self.__dict__ = cPickle.load(f)

# now I can do this...
t = Test()
t.new_data = 'hi there'

t1 = Test()
t1.new_data    # prints 'hi there'

More information about the Python-list mailing list