On May 18, 10:41 am, "inhahe" <[EMAIL PROTECTED]> wrote: > > Both the responses offer lambda free alternatives. That's fine, and > > given the terse documentation and problems that I had understanding > > them, I would agree. So what applications are lambdas suited to? I > > think the parameterised function model is one. > > What else? > > i've hardly ever used lambdas since map() and filter() were replaced by list > comprehension. two other uses I can think of for it are: using it as a > sorting key (which takes a function and lambdas are perfect for that when a > direct function isn't available. for example, lambda x: x.myName), and I > made an irc bot once that certain events had a list of fuctions that would > be called after that event. it was like being able to dynamically add and > remove event handlers. for example what if you asked the user a question > and you wanted to know for the next input whether it was from that user and > was an answer to that question. sometimes the function to add would be very > simple, so writing a def for it would just be ugly.
lambda is handy in defining parse actions in pyparsing. Parse actions are callbacks to be run when an expression within a larger grammar is matched. A common use for parse actions is to do some sort of text or type conversion. The simplest parse actions are called using the list of matched tokens. Here is a subexpression that will convert numeric strings found in a larger grammar to ints: integer = Word("0123456789").setParseAction(lambda tokens: int(tokens[0]) ) Since this returns an actual int, there is no need to junk up the post- parsing code with calls to int(), float(), etc. for these simple conversions. Here is an example parse action that just converts a set of matched words to title case: title = OneOrMore(Word(alphas)).setParseAction(lambda tokens: " ".join([ t.title() for t in tokens ]) ) print title.parseString("the sun also rises")[0] prints: The Sun Also Rises This second example is about as complex as I'd like to get in a lambda, though. Anything more elaborate than that, and I'd go with a separately defined function. -- Paul -- http://mail.python.org/mailman/listinfo/python-list