How to pickle a lambda function?

Duncan Booth duncan.booth at invalid.invalid
Tue Aug 11 09:42:06 CEST 2009


Terry <terry.yinzhe at gmail.com> wrote:

> 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?
> 

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.

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list