Serializing functions

Stephen Hansen me+list/python at ixokai.io
Thu Jun 17 11:31:45 EDT 2010


On 6/17/10 6:23 AM, Matteo Landi wrote:
> itself. If you try and pickle a function, it is not pickled as a whole,
> indeed, once you unpickle it, it will raise an exception telling you
> that the target function was not found in the current module.

You can pickle functions-- and classes, instances, and such-- just fine.
If you're having specific difficulty with one instance of doing so, show
the actual code.

>>> def test(one):
...     print one + 1
...
>>> import pickle
>>> outp = pickle.dumps(test)
>>> outp
'c__main__\ntest\np0\n.'
>>> fn = pickle.loads(outp)
>>> fn(1)
2

Now, complex stuff like classes and functions have to "live" in the same
place with pickle, and it does need the source to be available and
already imported, but it works fine.

If by "pickle a function" you mean, "take an arbitrary function and
pickle it into some random destination and have it by itself still be
enough to be executable", then no, pickle doesn't do that. To get that,
you'd have to distribute the source to the destination and import it
before-hand.

That or do some crazy-complicated sort of code object marshalling and
manipulation on the other side. I have no idea where to even begin in
that situation (hoooow do you turn a code object into something you can
actually pass arguments to, hmm? I only know how to 'exec' a bare code
object)

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 487 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20100617/35bda8ca/attachment.sig>


More information about the Python-list mailing list