Best way to pickle functions

Aaron Scott aaron.hildebrandt at
Fri Apr 3 19:50:33 CEST 2009

> Pickling the source code is much sturdier.  It's very unlikely that
> the same code runs differently in different interpreters.  It's much
> more likely that the same code runs the same, or not at all.

Okay, I've run into another problem. I've saved the code to a string,
so I can call it up when I need it. I want to keep these functions all
together, though, so I'm pushing them into a dictionary when I execute
it. It seems like when I put it in a dictionary, though, it messes up
the scope of the functions contained within. For example:

	import cPickle
	def Main():
		holder = {}
		functiontest = "def PickleTest():\n\tprint cPickle"
		exec functiontest in holder
		print holder["PickleTest"]()

... produces:

	Traceback (most recent call last):
	  File "", line 11, in <module>
	  File "", line 9, in Main
		print holder["PickleTest"]()
	  File "<string>", line 2, in PickleTest
	NameError: global name 'cPickle' is not defined

Is there any way to do this so that the functions have access to the
higher scope?


More information about the Python-list mailing list