Python code persistance

Andrés ahindra at
Thu Aug 29 02:44:33 CEST 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,

#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
#to build the code object

reconstructed = new.code


exec (reconstructed)

More information about the Python-list mailing list