explain this function to me, lambda confusion

Duncan Booth duncan.booth at invalid.invalid
Thu May 8 04:11:19 EDT 2008


andrej.panjkov at climatechange.qld.gov.au wrote:

> 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 ) 
)
> 
> (Because of the resemblance to C macros, I have been cautious and
> written the lambda with lots of parentheses.)
> 
> To use this in later code, we define instances of the lambda with
> specific function arguments.
> 
>>>> topping = XOR( cream, icecream)
>>>> sauce = XOR( tomato, BBQ )
> 
> 
> We now have two ­øfunctions­ñ, topping() and sauce() which we can use
> later to test flags.
> 
>>>> cream = True
>>>> icecream = False
>>>> print topping()
> True
> 

No, no, no, no, no!

You have got it entirely wrong here. Your XOR function simply returns a 
function which gives you the result of xoring the parameters AT THE TIME 
WHEN YOU ORIGINALLY CREATED IT. I'm guessing that you had already set 
cream and icecream (otherwise the call to XOR would have thrown an 
exception) and at leas one was true. Try setting them both False at the 
beginning:

>>> cream = False
>>> icecream = False
>>> topping = XOR( cream, icecream)
>>> cream = True
>>> icecream = False
>>> print topping()
False

Using a lambda was a completely pointless exercise here, you could have 
just returned the result directly:

>>> def XOR(x,y):
	return x^y

>>> topping = XOR(cream, icecream)
>>> print topping
True

Same thing for your TFF function:

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

AddOnly = TFF( options.AddAction, options.ReplaceAction,
options.DeleteAction )
DeleteOnly = TFF( options.DeleteAction, options.AddAction,
options.ReplaceAction )
ReplaceOnly = TFF( options.ReplaceAction, options.AddAction,
options.DeleteAction )

if not (DeleteOnly or AddOnly or ReplaceOnly):
  print "Error:  Exactly one of  [ --add | --replace | --delete ]
allowed. "
  parser.print_help()
  exit

which boils down to:

if (options.AddAction + options.ReplaceAction +
        options.DeleteAction) != 1:
    print "Error: ..."



More information about the Python-list mailing list