How to pickle bound methods

Peter Otten __peter__ at web.de
Thu Jul 3 08:43:45 CEST 2008


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



More information about the Python-list mailing list