[Python-ideas] Syntax for passing lambdas to functions
Joshua Landau
joshua at landau.ws
Fri Feb 28 00:38:56 CET 2014
On 27 February 2014 04:19, Steven D'Aprano <steve at pearwood.info> wrote:
> On Wed, Feb 26, 2014 at 11:44:51AM -0800, Andrew Barnert wrote:
>
>> But it becomes more useful if you do anything else:
>>
>> Button("Do it!", on_click() = fire_the_ducks(42))
>>
>>
>> At first glance, I think this is nice,
>
> At first glance, it looks like you are setting the on_click argument to
> the result of fire_the_ducks(42). This proposed syntax is going to be
> *really easy* for people to misinterpret when they see it in use. And
> not just novices -- I think this will be syntax that just begs to be
> misinterpreted when reading code, and misused when writing it.
>
> I think that having special syntax for anonymous function only inside
> function calls with keyword arguments is a violation of the Zen of
> Python (see the one about special cases) and the Principle Of Least
> Surprise. It's really a bad idea to have syntax for a "shorter lambda"
> that works here:
>
> f(arg=***whatever***)
>
> but not in these:
>
> f(***whatever***)
> [len, zip, map, ***whatever***, some_function]
> result = ***whatever***(arg)
I don't follow. I know it's different, but we have
f(*args) but not [*args]
And we have
start, *mid, end = [1, 2, 3] but not (lambda start, *mid, end: ...)(1, 2, 3)
and we have
(lambda x: ...)(*[...]) but not foo = *[...]
... *wink¹*
It's not silly to think that things are context-sensitive in a
context-sensitive language. Personally this proposal makes sense and I
honestly don't see the confusion that's being stated. It makes things
significantly prettier and more readable, for one.
Further, for consistency one can define:
matrix.transform((x, y)=(y, x))
as an "anonymous" version, compiling to
matrix.transform(lambda x, y: (y, x))
Please admit that this is way, way prettier.
PS: One problem. "f( (a) = ... )" is currently valid. So is "f(
(((((a))))) = ... )". Why the hell is this so? "(a) = 2" is valid, but
so is "(a, b) = (2, 3)", whereas "f( (a, b) = (2, 3) )" is not.
¹http://www.python.org/dev/peps/pep-0448/
More information about the Python-ideas
mailing list