By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,588 Members | 1,084 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,588 IT Pros & Developers. It's quick & easy.

How to pickle bound methods

P: n/a
Hi,
I would like*to know how to pickle a bound method??
Thanks,
Srini
Meet people who discuss and share your passions. Go to http://in.promos.yahoo.com/groups/bestofyahoo/
Jul 2 '08 #1
Share this Question
Share on Google+
1 Reply

P: n/a
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
Jul 2 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.