accessing a classes code

rx do_not_use_this_email at hotmail.com
Wed Apr 19 13:00:10 EDT 2006


"Ryan Krauss" <ryanlists at gmail.com> wrote in message 
news:mailman.4754.1145458893.27775.python-list at python.org...

Is there a way for a Python instance to access its own code
(especially the __init__ method)?  And if there is, is there a clean
way to write the modified code back to a file?   I assume that if I
can get the code as a list of strings, I can output it to a file
easily enough.



You are talking about writing code from and to a file. I think I had a 
similar problem, because I wanted a python class to contains some persistent 
runtime variables (fx the date of last backup) I didn't found a solution in 
the python library so I wrote a little class myself:

import cPickle
class Persistent:
    def __init__(self,filename):
        self.filename=filename
    def save(self):
        f=file(self.filename, 'wb')
        try:
            for i in vars(self):
                val=vars(self)[i]
                if not i[0:2]=='__':
                    cPickle.dump(i,f)
                    cPickle.dump(val,f)
        finally:
            f.close()
    def load(self):
        f=file(self.filename)
        try:
            while True:
                name=cPickle.load(f)
                value=cPickle.load(f)
                setattr(self,name,value)
        except EOFError:
            f.close()
        f.close()


You just use it like (the file has to exist - easy to change):

p=Persistent('file.obj')
p.load()
p.a=0.12345
p.b=0.21459
p.save()





More information about the Python-list mailing list