Pickling functions

Tim CHURCHES TCHUR at doh.health.nsw.gov.au
Tue Mar 27 03:15:29 EST 2001


How does one go about pickling and unpickling a function object? All my attempts so far
result in a reference to the function object being pickled but not the function itself.
For example:

################################################
def maketransform(name,code=None,path="/somewhere/"):
	import zlib, cPickle, new	filename =   path + name + "_transform.gsz"	f = open(filename, 'w+')	func = new.function(compile(code,'blah','exec'),{},name,(v,))	print func(1)	f.write(zlib.compress(cPickle.dumps(func, 1)))	f.close()
maketransform("sexlabel",code="""def sexlabel(v):	ldict = {1:"Male",2:"Female"}	try:		return ldict[v]	except:		return v""")#########################################

and then in a separate Python session

#########################################
def loadtransform(name,path="/somewhere/"):	import zlib, cPickle	filename =   path + name + "_transform.gsz"	f = open(filename, 'r+')	func = cPickle.loads(zlib.decompress(f.read()))	f.close()	return func		sexlabel = loadtransform("sexlabel")print sexlabel(1)##########################################

does not work - Python reports a NameError because function sexlabel can't be found in __main__
What am I doing wrong? Is there a simpler way of doing this?

Tim C






More information about the Python-list mailing list