How to pickle bound methods

srinivasan srinivas sri_annauni at yahoo.co.in
Wed Jul 2 07:14:29 EDT 2008


HI Peter,
It works will for instance and class methods. But it doesn't work for static methods.
Can you tel me how to pickle static methods as well??
Thanks,
Srini

----- Original Message ----
From: Peter Otten <__peter__ at web.de>
To: python-list at python.org
Sent: Wednesday, 2 July, 2008 12:53:19 PM
Subject: Re: How to pickle bound methods

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


      Bring your gang together. Do your thing. Find your favourite Yahoo! group at http://in.promos.yahoo.com/groups/



More information about the Python-list mailing list