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

Peter Otten __peter__ at web.de
Tue Apr 3 03:54:50 EDT 2012


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.

> & maybe suggest a
> workaround, (apart from the obvious if ... elif...).

You can implement pickling yourself:

import copy_reg 
import types

def pickle_instancemethod(m):
    return unpickle_instancemethod, (m.im_func.__name__, m.im_self, 
m.im_class) 
 
def unpickle_instancemethod(name, im_self, im_class):
    im_func = getattr(im_class, name)
    return im_func.__get__(im_self, im_class) 
 
copy_reg.pickle(types.MethodType, pickle_instancemethod) 

 
> I'm running Python 2.6 on an embedded system.
> 
> == testpickle.py ==
> import pickle
> 
> class Test(object):
>     def __init__(self):
>         self.myDict = {
>             1: self.tag1,
>             2: self.tag2
>             }
>     def dispatch(self, v):
>         try:
>             self.myDict[v]()
>         except KeyError:
>             print "No corresponding dictionary entry!"
>         #
>     def tag1(self):
>         print "one"
>     def tag2(self):
>         print "two"
> 
> 
> t = Test()
> t.dispatch(1)
> t.dispatch(2)
> t.dispatch(0)
> 
> fd = open("pickle.out", "w")
> pickle.dump(t, fd)
> fd.close()
> # EOF
> 
> $ python testpickle.py
> one
> two
> No corresponding dictionary entry!

> TypeError: can't pickle instancemethod objects
> $





More information about the Python-list mailing list