How to pickle bound methods

  • Thread starter srinivasan srinivas
  • Start date
P

Peter Otten

srinivasan said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top