Replace lambda with normals?

Steven D. Majewski sdm7g at Virginia.EDU
Thu May 3 20:37:41 EDT 2001


On Thu, 3 May 2001, scott wrote:

> I'm going through the 'Dive into Python' tutorial and hit lambdas. I
> know they are optional. As a beginner I would probably prefer they
> weren't a language feature. Too many ways to do it. Anyway...
> Question:
> How would I replace the 2 lambdas in the following code from chapter 2
> with normal functions?
> ----------------------------------------

> ---------------------------------------
> 
> I tried creating separate functions and calling the functions e.g.:
> #added new functions to the module e.g.
> def shrinkIt(s):
>     return " ".join(s.split())
> #tried to call it
> processFunc = collapse and shrinkIt() or leaveIt()
> 
> Of course it didn't work. How do I do it right?
> Thanks in advance.
> 

The parends appended to shrinkIt and leaveIt turn those into
function CALLS, not function references. You just want the
name there -- 

  processFunc = collapse and shrinkIt or leaveIt 

processFunc should be a reference to a function -- whether that
function was named with 'def' or created as a lambda expression.
The function/lambda  call is done when  processFunc() is called. 

( However: defender of the Lambda expression that I am, I would
  probably not use one there in that manner. An if statement 
  would probably be cleaner -- especially as there's only 
  two options. If I had a dozen options, I'ld probably stuff 
  them in a table -- whether they were named or anonymous 
  functions. )  

-- Steve Majewski






More information about the Python-list mailing list