Serializing functions

Andreas Löscher andreas.loescher at s2005.tu-chemnitz.de
Thu Jun 17 12:03:06 EDT 2010


Am Donnerstag, den 17.06.2010, 08:18 -0700 schrieb Paul Rubin:
> Matteo Landi <landimatte at gmail.com> writes:
> > I could be wrong, but it seems functions are not marshable objects, is
> > it right?
> 
> Hmm, you're right, you can marshal code objects, but you can't marshal a
> function directly.  It's been a while since I've used marshal and I
> forgot how it works.  You might be able to concoct something around it,
> but it could be messy.  It may be simplest to send the other side a
> python source file that it can import.

There was a similar thread a while ago.

You can marshal the functions code object and create a new function on
the remote side using this code object.

>>> import marshal
>>> def spam(): pass

now marshal the code object

>>> s = marshal.dumps(spam.func_code)

On the remote side:

>>> import marshal
>>> import types
>>> code = marshal.loads(s)
>>> spam = types.FunctionType(code, globals())

This works as long as you are using byte code compatible Versions on
both side. The creation of functions has also some optional arguments
you must be aware of, in order to get the result you want. 

Look at help(types.FunctionType) for further information.






More information about the Python-list mailing list