How to pickle a lambda function?

T

Terry

Hi,

I'm trying to implement something like:

remote_map(fun, list)

to execute the function on a remove machine. But the problem is I
cannot pickle a lambda function and send it to the remote machine.

Is there any possible way to pickle (or other method) any functions
including lambda?

br, Terry
 
T

Terry

You can pickle any named functions that are declared at module scope.

You cannot pickle anonymous functions, methods, or functions declared
nested inside other functions. The function must be present in the same
module when you unpickle it, and if the definition has changed between
pickling and unpickling the new definition will be used (just as other
instances will use the current class definition not the one they were
pickled with).

You probably could pickle some of the components needed to create your
lambda and construct a new function from it when unpickling: try the code
object, the name of the module to be used for the globals, and default
arguments. I don't think you can pickle the closure so better make sure
your lambda doesn't need one, and be very careful to ensure that you
restore the pickle in the same version of Python otherwise the code object
might break. Best just avoid this and use named functions for anything that
needs pickling.

Yes, I'm think of pickle (actually marshal) the code object. Otherwise
I have to use string and eval:-(

The reason I need to be able to pickle any function is because I want
my remote machine knows nothing about the function before receiving
it, so I don't need to update the source code in the remote machine
very often.

br, terry
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,045
Latest member
DRCM

Latest Threads

Top