why can't I pickle a class containing this dispatch dictionary?

Peter Otten __peter__ at web.de
Tue Apr 3 10:44:09 EDT 2012


jkn wrote:

> Hi Peter
> 
> On Apr 3, 8:54 am, Peter Otten <__pete... at web.de> wrote:
>> jkn wrote:
>> > I'm clearly not understanding the 'can't pickle instancemethod
>> > objects' error; can someone help me to understand,
>>
>> I think classes implemented in C need some extra work to make them
>> picklable, and that hasn't been done for instance methods.
> 
> by 'classes implemented in C', doyou mean new-style classes', or what,
> please?

Given 

>>> class A(object):
...     def __init__(self, name):
...             self.name = name
...     def hello(self):
...             print "Hello,", self.name
... 
>>> a = A("Peter")
>>> hello = a.hello
>>> hello()
Hello, Peter

the object bound to the name 'hello' is an instance of the 'instancemethod' 
type:

>>> type(hello)
<type 'instancemethod'>

That type is implemented in C, see

http://hg.python.org/cpython/file/9599f091faa6/Objects/classobject.c

and doesn't support the pickle protocol while a similar class, 
functools.partial which is also written in C, see

http://hg.python.org/cpython/file/9599f091faa6/Modules/_functoolsmodule.c

does:

>>> from functools import partial
>>> import pickle
>>> def hello(obj):
...     print "Hi,", obj.name
... 
>>> hello2 = partial(hello, a)
>>> hello2()
Hi, Peter
>>> s = pickle.dumps(hello2)
>>> pickle.loads(s)()
Hi, Peter





More information about the Python-list mailing list