A critic of Guido's blog on Python's lambda

Alex Martelli aleaxit at yahoo.com
Mon May 8 01:09:35 EDT 2006


Frank Buss <fb at frank-buss.de> wrote:

> Alex Martelli wrote:
> 
> > Not sure what the &key means here, but omitting that
> > 
> > def black_white(function, limit):
> >     def result(x,y):
> >         if function(x, y) > limit: return 1.0
> >         else: return 0.0
> >     return result
> 
> &key is something like keyword arguments in Python. And looks like you are

Ah, thanks.

> right again (I've tested it in Pyhton) and my assumption was wrong, so the
> important thing is to support closures, which Python does, even with local
> function definitions.

We do appear to entirely agree.  In Python <= 2.4, where if is just a
statement (not an expression), you'd need some trick to get this effect
with a lambda, e.g.:

def black_white(function, limit, key=None):
    return lambda x,y: 1.0 * (function(x,y) > limit)

assuming it's important to get a float result -- the > operator per se
returns an int, so you can call float() on it, or multiply it by 1.0,
etc -- if you had two arbitrary colors, e.g.

def two_tone(function, limit, key=None, low=0.0, high=1.0):
    return lambda x,y: (low, high)[function(x,y) > limit]

which is a pretty obscure alternative.  In Python >= 2.5, an if
expression has been added, but I'll leave you to judge if it's actually
an improvement (sigh)...:

def two_tone(function, limit, key=None, low=0.0, high=1.0):
    return lambda x,y: high if function(x,y) > limit else low

Personally, I'd rather use the named-function version.  Anyway, they're
all semantically equivalent (sigh), and the key point is that the
semantics (building and returning functions on the fly) IS there,
whether the functions are named or unnamed, as we agree.


Alex



More information about the Python-list mailing list