Multi-line lambda proposal.

Kaz Kylheku kkylheku at gmail.com
Wed May 10 13:51:59 EDT 2006


Antoon Pardon wrote:
> Could you give me an example. Suppose I have the following:
>
> def arg_range(inf, sup):
>
>   def check(f):
>
>     def call(arg):
>       if inf <= arg <= sup:
>         return f(arg)
>       else:
>         raise ValueError
>
>     return call
>
>   return check

def arg_range(inf, sup)
  return lambda(f):
    return lambda(arg):
      if inf <= arg <= sup:
        return f(arg)
      else
        raise ValueError

Nice; now I can see what this does: returns a function that, for a
given function f, returns a function which passes its argument arg to f
if the argument is in the [inf, sup] range, but otherwise raises a
ValueError. The English description pops out from the nested lambda.

The names in the inner-function version only serve to confuse. The
function check doesn't check anything; it takes a function f and
returns a validating function wrapped around f.

In fact, an excellent name for the outer-most inner function is that of
the outer function itself:

def range_checked_function_maker(inf, sup):

  def range_checked_function_maker(f):

    def checked_call_of_f(arg):
      if inf <= arg <= sup:
        return f(arg)
      else:
        raise ValueError

    return checked_call_of_f

  return range_checked_function_maker

This alone makes a good case for using an anonymous function: when you
have a function which does nothing but return an object, and that
function has some noun as its name, it's clear that the name applies to
the returned value.

This:

  def forty_two():
    return 42

is not in any way made clearer by:

  def forty_two():
    forty_two = 42
    return forty_two

:)




More information about the Python-list mailing list