How to pickle a lambda function?

Terry terry.yinzhe at gmail.com
Tue Aug 11 10:16:14 CEST 2009


On Aug 11, 3:42 pm, Duncan Booth <duncan.bo... at invalid.invalid> wrote:
> Terry <terry.yin... 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 Boothhttp://kupuguy.blogspot.com

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



More information about the Python-list mailing list