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

Michael Hrivnak mhrivnak at hrivnak.org
Mon Apr 2 18:48:45 EDT 2012


Pickle cannot pickle a reference to an instance method.  So the
problem is that self.myDict has values which are references to
instance methods.

Without questioning what this is trying to do or why (I assume it's a
proof of concept), here is a way to make it picklable:
http://pastebin.com/1zqE52mD

Michael

On Mon, Apr 2, 2012 at 7:17 AM, jkn <jkn_gg at nicorp.f9.co.uk> wrote:
> Hi All
>    I'm clearly not understanding the 'can't pickle instancemethod
> objects' error; can someone help me to understand, & maybe suggest a
> workaround, (apart from the obvious if ... elif...).
>
> 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!
> Traceback (most recent call last):
>  File "ptest.py", line 29, in <module>
>    pickle.dump(t, fd)
>  File "/usr/lib/python2.6/pickle.py", line 1362, in dump
>    Pickler(file, protocol).dump(obj)
>  File "/usr/lib/python2.6/pickle.py", line 224, in dump
>    self.save(obj)
>  File "/usr/lib/python2.6/pickle.py", line 331, in save
>    self.save_reduce(obj=obj, *rv)
>  File "/usr/lib/python2.6/pickle.py", line 419, in save_reduce
>    save(state)
>  File "/usr/lib/python2.6/pickle.py", line 286, in save
>    f(self, obj) # Call unbound method with explicit self
>  File "/usr/lib/python2.6/pickle.py", line 649, in save_dict
>    self._batch_setitems(obj.iteritems())
>  File "/usr/lib/python2.6/pickle.py", line 663, in _batch_setitems
>    save(v)
>  File "/usr/lib/python2.6/pickle.py", line 286, in save
>    f(self, obj) # Call unbound method with explicit self
>  File "/usr/lib/python2.6/pickle.py", line 649, in save_dict
>    self._batch_setitems(obj.iteritems())
>  File "/usr/lib/python2.6/pickle.py", line 663, in _batch_setitems
>    save(v)
>  File "/usr/lib/python2.6/pickle.py", line 306, in save
>    rv = reduce(self.proto)
>  File "/usr/lib/python2.6/copy_reg.py", line 70, in _reduce_ex
>    raise TypeError, "can't pickle %s objects" % base.__name__
> TypeError: can't pickle instancemethod objects
> $
>
>
>    Thanks
>    J^n
>
> --
> http://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list