problem pickling a function

Emin.shopper Martinian.shopper emin.shopper at gmail.com
Wed Dec 12 12:10:43 EST 2007


On Dec 12, 2007 11:48 AM, Calvin Spealman <ironfroggy at socialserve.com>
wrote:

> On Dec 12, 2007, at 11:01 AM, Emin.shopper Martinian.shopper wrote:
>
> > But is there a way to assign functions to instances of a class
> > without preventing pickleability? It doesn't seem unreasonable to
> > me to want to assign functions to instances of a class (after all
> > functions are first class objects, so why shouldn't I be able to
> > pass them around?) Is there a better way or is this just a
> > limitation of pickle?
>
> Presumably you could do something with __getstate__ and __setstate__
> methods, but this is many cases of "Are you really sure you want to
> do that?"
>
>
Why is it unreasonable to want to pass functions as arguments to classes? If
functions are first class arguments, that seems perfectly reasonable to me.

I guess the best work around is to put the desired function into a
staticmethod as shown below:

>>> class f: pass
>>> g = f()
>>> class j:
    @staticmethod
    def join(*args,**kw):
         return ','.join(*args,**kw)
>>> g.x=j
>>> import pickle; pickle.dumps(g)
'c__main__\nj\np0\n.

The above provides a way to pickle functions but it seems like a bit of a
hack...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20071212/f5e091d1/attachment.html>


More information about the Python-list mailing list