explain this function to me, lambda confusion

Terry Reedy tjreedy at udel.edu
Thu May 8 00:40:27 EDT 2008


<andrej.panjkov at climatechange.qld.gov.au> wrote in message 
news:b2b7ff0b-922e-4ecf-9d04-50ce22243624 at a9g2000prl.googlegroups.com...

| On May 8, 7:38 am, globalrev <skanem... at yahoo.se> wrote:
| I would describe a lambda as a parameterised function template. If you
| dig, the docs call lambdas anonymous functions not bound to a name.

A lambda expression is an abbreviation of a simple def statement:
f = lambda args: expression
def f(args): return expression
have exactly the same effect except that f.func_name will be the less 
useful '<lambda>' instead of the more useful 'f'.

| There is a bit of resemblance to C macros.

Macros in C (and, I believe, some places elsewhere) are text-replacement 
templates.  They are markedly different from function statements.  C macros 
do not create C functions.  Python lambda expression do create Python 
function objects.  Since C macros are statements, not expressions, and are 
introduced by #define, similar to def, one could argue than Python def 
statements are more similar to C macros.

| Here is a simple lambda that implements an exclusive or:
|
| >>> def XOR(x,y) :
| >>>   return lambda : ( ( x ) and not ( y ) ) or ( not ( x ) and ( y ) )

def XORY(x,y):
   def _xory(): x and not y or not x and y
   return _xory

has the same effect.  Because lambda expressions define functions, not 
macros, there is no need for the protective parentheses that macros need.

 Here is another simple lambda, (template) to set up three new
| functions AddOnly, DeleteOnly, and ReplaceOnly.
|
| #--# Lambda function to check that a flag is only on when the other
| two are off. #--#
| def TFF(x,y,z) :
|  return lambda : ( ( x ) and not ( y ) and not ( z ) )

def TFF(x,y,z):
   def _tff(x,y,z): return ( ( x ) and not ( y ) and not ( z ) )
   return _tff

Same result (except for a real name in tracebacks), same usage.

| >>> import math
| >>> def Gaussian( mu, sigma ) :
| ...   return lambda x : math.exp( - (x-mu)**2 / 2 /sigma**2 ) /
| math.sqrt (2 * math.pi *sigma **2 )

def Gaussian(mu, sigma):
   def _gaussian(x): return math.exp( - (x-mu)**2 / 2 /sigma**2 ) /
      math.sqrt (2 * math.pi *sigma **2 )
   return _gaussian

Again, giving the returned function a name will help a bit if it raises an 
exception, which is definitely possible here.

Lambda expressions are an occasional convienience, not a requirement. 
Anyone who is confused by what they do should use an equivalent def 
instead.

Terry Jan Reedy






More information about the Python-list mailing list