Lambda alternative?

Aaron Brady castironpi at gmail.com
Thu Apr 16 07:15:47 EDT 2009


On Apr 16, 5:25 am, mousemeat <mousem... at gmail.com> wrote:
> On 16 Apr, 10:21, Hrvoje Niksic <hnik... at xemacs.org> wrote:
>
>
>
> > mousemeat <mousem... at gmail.com> writes:
> > > Thank you for everyone's explanations, help and interest on this
> > > one.  I have reworked my code as described and promised myself not
> > > to use lambdas ever again (i still think they are an elegant idea,
> > > but if they are incompatible with frequently used modules, then the
> > > inelegance of reality quickly overshadows the elegance of the
> > > theory).
>
> > I think you're going too far concluding that lambdas are unusable.
> > lambdas are a problem only when they are stored as data attributes
> > that need to be pickled, but that's far from being the only use case.
> > You can still use them for what they're meant to be used: tiny anonymous
> > function-expressions, typically passed as parameters to functions that
> > expect a callback.
>
> > Avoiding lambdas because they're unpicklable is like avoiding bound
> > methods because they're just as unpicklable.
>
> Correct me if i am wrong, but i can pickle an object that contains a
> bound method (it's own bound method).  I cannot pickle an object that
> contains a lambda function.  Doesn't that make lambda's less
> pickleable?  (I don't mean to be argumentative, i'm trying to
> understand python's syntax a little better.)

When you pickle an instance, you get its data and the name of its
class.  If you don't have the class later, you can't unpickle it.

Pickle is intended for persistence, and the only real kinds of
persistent code are a self-contained library file, and the source,
especially given access to function-external variables, i.e.
closures.  Pickling a function is like taking an excerpt from a binary
executable.  It can only be used in highly limited contexts, and as
such not good for a standard module.

It is most likely you want to transmit the source-- either the entire
module, which you can then import dynamically, or an excerpt from it,
which is known to have no closures, etc., and carefully call 'eval' on
it.

I disagree that Andres Tremols & Peter Cogolo's 'Recipe 7.6. Pickling
Code Objects' is applicable.  It's highly specialized, delicate, and
brittle.



More information about the Python-list mailing list