The main problem with your code is the closuse in "sample_function". Without the closure, it can be done with marshal and types modules, here's some example:
import pickle
import marshal
import types
class Foo():
def __init__(self, fun):
self.fun = fun
def call_fun(self, arg):
self.fun(arg)
def save(self, f):
saved = self.fun
self.fun = marshal.dumps(self.fun.func_code)
pickle.dump(self, f)
self.fun = saved
@staticmethod
def load(f):
foo = pickle.load(f)
foo.fun = types.FunctionType(marshal.loads(foo.fun), globals())
return foo
def sample_function(arg):
arg.effect(4)
class Arg():
def effect(self, value):
print "ok: " + str(value)
With this classes and function, you can save:
foo = Foo(sample_function)
f = open('foo', 'w')
foo.save(f)
f.close()
and load:
f = open('foo', 'r')
foo = Foo.load(f)
f.close()
The idea is to marshal the "fun" before pickling (and restore it, so the class is not broken) and to load the marshaled code as a function when loading.
But that won't works with closures (because the closure needs variables from the calling function).