Why can't you pickle instancemethods?

mdsteele at gmail.com mdsteele at gmail.com
Fri Nov 10 19:36:57 EST 2006


Steven Bethard wrote:
> Here's the recipe I use::
>
>      [...]
>
> There may be some special cases where this fails, but I haven't run into
> them yet.

Wow, that's a really nice recipe; I didn't even know about the copy_reg
module.  I'll have to start using that.

I did notice one failure mode, however--it doesn't work with methods
named __foo because im_func.__name__ contains the *unmangled* version
of the function name, so when you try to unpickle the method, the try
statement never succeeds and you get an UnboundLocalError on func.

The good news is that I think it can be fixed by mangling the name
manually in _pickle_method(), like so:

def _pickle_method(method):
    func_name = method.im_func.__name__
    obj = method.im_self
    cls = method.im_class
    if func_name.startswith('__') and not func_name.endswith('__'):
        cls_name = cls.__name__.lstrip('_')
        if cls_name: func_name = '_' + cls_name + func_name
    return _unpickle_method, (func_name, obj, cls)




More information about the Python-list mailing list