[Python-ideas] a new lambda syntax
Steven D'Aprano
steve at pearwood.info
Tue Oct 20 13:21:02 CEST 2009
On Tue, 20 Oct 2009 07:39:44 pm Masklinn wrote:
> On 20 Oct 2009, at 01:06 , Steven D'Aprano wrote:
> > If your "anonymous code block" is more complicated than a single
> > short expression, it's too complicated to be "obviously correct"
> > just from looking at it, and so it should be documented and tested.
>
> I have the same issue with this as with Oleg's pronouncement (which
> runs along the same lines): does that mean you never write for or if
> statements with more than a single line in them?
No, you are correct, my statement is overly strong. Please insert "very
likely" between "it's" and "too complicated".
> Yet these are also "anonymous code blocks" which you say here are
> "too complicated to be obviously correct just from looking at
> [them]".
>
> If that's the case, why should compound statements even be allowed?
> They're breeding grounds for multiline anonymous blocks of code…
There is at least one difference between compound statements and
multi-statement anonymous code blocks:
You don't pass compound statements around as input to other functions,
so you know the environment that they're being called in, and can more
easily reason about their correctness.
But even then, compound statements are good candidates for being
converted into named functions too. I usually start with something like
this:
if cond:
do this
do that
do something else
fe
fi
fo
fum
...
else:
one fish
two fish
red fish
blue fish
...
and by the time I'm finished I've got something like this:
if cond:
call_one()
else:
call_two()
The multi-line blocks are split into functions, each with their own
documentation and tests.
Of course I don't do this literally every single time. There's no hard
rule about how many lines are allowed, just like there's no hard rule
about how complex a data structure can be before you give it a name.
But my point is that the restriction on lambda is not an odious one, or
at least not so odious that it deserves the amount of heat that it
generates. There are uses for multi-statement anonymous functions, but
there is nothing that an anonymous function can do that a named
function can't.[1]
In my opinion, it simply isn't enough of a burden to define a function
before you use it, using a "don't care" name, to deserve the amount of
words written about potential multi-statement lambda syntax. If Python
had different syntax, then perhaps we'd have anonymous functions like
Ruby. But we don't, and frankly I don't think it is much of a
restriction.
[1] Some way to write an anonymous code block, which isn't a function
and simply runs in the local environment where it is called as if it
were written in-line, would be more interesting to me.
--
Steven D'Aprano
More information about the Python-ideas
mailing list