How to pickle bound methods
srinivasan srinivas
sri_annauni at yahoo.co.in
Thu Jul 3 04:23:08 EDT 2008
No. It does not work.
def make_staticmethod(inst, methodname):
return getattr(inst, methodname)
def pickle_function(method):
return make_staticmethod, (method.im_self, method.im_func.__name__)
copy_reg.pickle(new.function, pickle_function, make_staticmethod)
----- Original Message ----
From: Peter Otten <__peter__ at web.de>
To: python-list at python.org
Sent: Thursday, 3 July, 2008 12:13:45 PM
Subject: Re: How to pickle bound methods
srinivasan srinivas wrote:
Please don't top-post.
> Could you please explain the code breifly?? I am not getting what it does.
>> 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 you have a type that cannot be pickled because it is implemented in C you
can make it "picklable" by registering it with the copy_reg.pickle()
function. This function takes three arguments:
1 the type (here: new.instancemethod)
2 a function that takes an instance of the type. This returns a factory
function and a tuple of the arguments this factory function needs to
recreate the instance.
3 the factory function.
In short the following must work, and out_method should do the same thing as
in_method:
factory, args = pickle_instancemethod(in_method)
out_method = factory(*args)
Now to your other problem, pickling static methods. The type of a static
method is just new.function, the same as that of a global function. Global
functions are already picklable, so the copy_reg mechanism doesn't kick in.
Peter
--
http://mail.python.org/mailman/listinfo/python-list
Unlimited freedom, unlimited storage. Get it now, on http://help.yahoo.com/l/in/yahoo/mail/yahoomail/tools/tools-08.html/
More information about the Python-list
mailing list