Anonymus functions revisited

Diez B. Roggisch deetsNOSPAM at
Wed Mar 23 12:06:34 CET 2005

> Can someone who thinks this way, please explain why this is acceptable
>   [ x * x for x in some_iterator ]
> But this is not
>   map(lambda x: x * x, some_iteraror)
> and should be replaced with
>   def sqr(x): return x * x
>   map(sqr , some_iterator)

It shouldn't, it should be replaced with the listcomp. And IMHO it results
in better readable code. 

AFAIK the reason people say you should use named functions is _not_ because
of these single expression replacements. The reason is that frequently
people complain about lambda being so restrictive so that you can't write

lambda x,y: if x > 100: x else: y

and want to _extend_ lambda beyond its current capabilities and make it full
featured but anonymous functions.

And these requests are rebuked with the argument that having to give a more
complex function a name instead of declaring it anonymously doesn't cost
you much - especially since you can declare them inside other functions so
the global namespace isn't cluttered.

I have to admit that rereading my statement

You are right, but for lambda in its current limited form short, named
functions are a good replacement

is not really what I wanted to say.

I should have written:

for lambda in its current limited form, listcomprehensions often are a good

But as I've said various times before: I personally don't mind lambdas and
for example the reduce function has been useful for me quite a few times,
can't be replaced by listcomps, and frequently needs a callable consisting
of only a single expression. So I'll continue to use lambdas there.


Diez B. Roggisch

More information about the Python-list mailing list