[Python-porting] Pickling unbound methods on Python 3

cool-RR cool-rr at cool-rr.com
Fri May 28 21:55:28 CEST 2010


Hello,

I've had a problem when porting my project from Python 2.6 to Python 3.x.

At some point in my project I need to be able to pickle unbound methods.

In Python 2.x it's impossible to pickle unbound methods by default; I
managed to do it there in some weird way I don't understand: I wrote a
reducer with the `copy_reg` module for the MethodType class, which covers
both bound and unbound methods. But the reducer only solved the case of the
bound method, because it depended on `my_method.im_self`. Mysteriously it
has also caused Python 2.x to be able to pickle unbound methods. This does
not happen on Python 3.x.

When trying to pickle a method, I'm getting this error:

    >>> class A:
    ...     def m(self):
    ...         pass
    >>> import pickle
    >>> pickle.dumps(A.m)
    Traceback (most recent call last):
      File "<pyshell#3>", line 1, in <module>
        pickle.dumps(A.m)
      File "C:\Python31\lib\pickle.py", line 1358, in dumps
        Pickler(f, protocol, fix_imports=fix_imports).dump(obj)
    _pickle.PicklingError: Can't pickle <class 'function'>: attribute lookup
builtins.function failed

How can this been solved?

One person told me that given an unbound method in Python 3.x, it's
*impossible* to tell to which class it belongs. Is it true?

Ram.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-porting/attachments/20100528/c68e116a/attachment.html>


More information about the Python-porting mailing list