Why can't pickle dump this instance?

Thomas D'Tak outpost at rumblefish.org
Fri Aug 13 07:00:56 EDT 2004


On Thu, 12 Aug 2004 22:46:27 -0700, Jane Austine wrote:

> class A:
>     def __init__(self,tick):
>         if tick:
>             self.foo=self.bar
>         else:
>             self.foo=self.bur
>     def bar(self):
>         print 'bar'
>     def bur(self):
>         print 'bur'
> 
> import pickle
> pickle.dumps(A())
> 
> running this script results in "TypeError: can't pickle function objects"
> 
> Why does this happen? and what can I do?

Running this script should actually result in

    TypeError: __init__() takes exactly 2 arguments (1 given)

because you did not write

    def __init__(self, tick=None):


But coming back to your original problem, have a look at the
following code:

    def bar():
        print 'bar'

    def bur():
        print 'bur'
    
    class A:
        def __init__(self,tick=None):
            if tick:
                self.foo=bar
            else:
                self.foo=bur

    import pickle
    pickle.dumps(A())

The above will do what you want. Have a look at the Python
Library Reference's
 
    3.14.4 What can be pickled and unpickled?
    http://www.python.org/doc/2.3.4/lib/node65.html

to see, why this works while the other script does not.

HTH, Th.




More information about the Python-list mailing list