How to pickle bound methods
Peter Otten
__peter__ at web.de
Wed Jul 2 03:23:19 EDT 2008
srinivasan srinivas wrote:
> I would like to know how to pickle a bound method??
$ cat pickle_method.py
import copy_reg
import new
def make_instancemethod(inst, methodname):
return getattr(inst, methodname)
def pickle_instancemethod(method):
return make_instancemethod, (method.im_self, method.im_func.__name__)
copy_reg.pickle(new.instancemethod, pickle_instancemethod,
make_instancemethod)
if __name__ == "__main__":
import pickle
class A(object):
def __init__(self, who):
self.who = who
def alpha(self):
print "Hello,", self.who
FILENAME = "method.pickle"
import sys
args = sys.argv[1:]
if args:
a = A(args[0])
m = a.alpha
pickle.dump(m, open(FILENAME, "wb"))
else:
m = pickle.load(open(FILENAME, "rb"))
m()
$ python pickle_method.py world
$ python pickle_method.py
Hello, world
$ python pickle_method.py Srini
$ python pickle_method.py
Hello, Srini
Peter
More information about the Python-list
mailing list