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
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to