Ian Bicking: the old part of his blog

Anonymous functions

My personal feeling is that a multi-line lambda is a mistake, like Guido says. However, I agree with the functionally oriented people that having to use a local named function breaks code locality and tends to make it hard to follow the code in Python written with a more functional flavor.

I think that the right Pythonic answer is to introduce a syntax kind of like ruby blocks where a function call can optionally be followed by a colon, then arg list and a suite underneath and that the arguments and suite would be converted to a local function passed as the last argument to the function. Here is an example:

def open_in( filename, block ):
  f = open( filename )
  try:
     return block( f )
  finally:
     close(f)


max_char = open_in( "foo.txt" ): (f)
  x = 0
  for l in f:
     x = max(x, len(l))
  return x

Or something like that. There are a few warts:

To see what I mean about the return or yield thing, here is an example. First the new form of reduce:

def reduce( l, v, f ):
  for x in l:
    v = f( v, x )
  return initial

Now, the clunky way to write a sum:

sum = reduce( x, 0 ): (a,b)
    return a+b

Vs, the more elegant (IMHO):

sum = reduce( x, 0 ): (a,b)
    a+b

However, sum is a simple contrived example because of course sums, products, any, and all should be built in, and possibly the only real uses involve suites large enough that return or yield is help in understanding, instead of a hindrance.

Comment on My Python 4k
by Alan Falloon