how to pickle a lambda?

Kragen Sitaker kragen at pobox.com
Wed May 1 21:06:46 EDT 2002


Paul Rubin <phr-n2002a at nightsong.com> writes:
> Kragen Sitaker <kragen at pobox.com> writes:
> > Unfortunately not.  You can't marshal lambdas either.
> 
> Oh well.  I'm surprised by this.  Maybe marshal should be extended.

You can't marshal functions of any kind.

> > Or you can just use named functions, especially if you don't have
> > closure data.
> 
> I thought a named function was just a variable whose value was a lambda:
>   def square(x): return x*x
> is the same as
>   square = lambda x: x*x

Approximately, yes.

> Of course the syntax is different (you can't have control statements in
> a lambda) but I'd have thought if you can't marshal a lambda, you also
> can't marshal a named function.

You can't marshal a named function, but you can pickle it; pickle
remembers the module and the function name.  For lambdas, all it gets
is <lambda>, which it can't unpickle; for named functions, it imports
the module (if necessary) and grabs the reference to the function by
name.

Which is why the original poster was saying his named functions were
working, but lambda's weren't.




More information about the Python-list mailing list