Why can't you pickle instancemethods?

Steven Bethard steven.bethard at gmail.com
Fri Oct 20 22:45:57 EDT 2006


Chris wrote:
> Why can pickle serialize references to functions, but not methods?

Here's the recipe I use::

     def _pickle_method(method):
         func_name = method.im_func.__name__
         obj = method.im_self
         cls = method.im_class
         return _unpickle_method, (func_name, obj, cls)

     def _unpickle_method(func_name, obj, cls):
         for cls in cls.mro():
             try:
                 func = cls.__dict__[func_name]
             except KeyError:
                 pass
             else:
                 break
         return func.__get__(obj, cls)

     import copy_reg
     import types
     copy_reg.pickle(types.MethodType, _pickle_method, _unpickle_method)

There may be some special cases where this fails, but I haven't run into 
them yet.

STeVe



More information about the Python-list mailing list