Python code persistance

Andrés ahindra at hotmail.com
Wed Aug 28 20:44:33 EDT 2002


I posted a reply earlier but maybe it got lost or its just delayed,
anyways I improved the code. Note that pickle or marshall don't
support persistence of code objects . the py_compile.compile may also
work but it works with files only and not strings.


import new
import pickle

#the string with code
mycode = "a =2+2\nprint a"

#the built-in compile() function converts it to
#a code object (compiles it)

mycodeobj = compile (mycode,'<string>','exec')


#a tuple is made storing all the code object properties needed
#for new.code()

codetup = (mycodeobj.co_argcount,mycodeobj.co_nlocals,mycodeobj.co_stacksize,
mycodeobj.co_flags, mycodeobj.co_code,mycodeobj.co_consts,mycodeobj.co_names,
mycodeobj.co_varnames,mycodeobj.co_filename,
mycodeobj.co_name,mycodeobj.co_firstlineno,mycodeobj.co_lnotab)

#the tuple is dumped into a string or file (string in this case)

codedump = pickle.dumps(codetup)

#at this point the codedump variable is a string
#so it can be stored in a database
#and then retrieved like:

coderecover = pickle.loads(codedump)

#now the new.code() function is used, the retrieved tuple contains all
information
#to build the code object

reconstructed = new.code
(coderecover[0],coderecover[1],coderecover[2],coderecover[3],coderecover[4],coderecover[5],coderecover[6],
coderecover[7],coderecover[8],coderecover[9],coderecover[10],coderecover[11])

#...

exec (reconstructed)



More information about the Python-list mailing list