[Python-ideas] Syntax for passing lambdas to functions

Greg Ewing greg.ewing at canterbury.ac.nz
Wed Feb 26 23:16:45 CET 2014


Andrew Barnert wrote:
> Button("Do it!", on_click() = fire_the_ducks(42))
> 
> At first glance, I think this is nice, but there's a nagging feeling that it
> may be a bit magical. Maybe if I think through what the compiler will do with
> it, I can resolve that feeling.

It's quite simple, it's just syntactic sugar for

    Button("Do it!", on_click = lambda: fire_the_ducks(42))

> We'd be adding:
> 
>     Button("Do it!", on_click()=fire_the_ducks()) # good
> 
>     Button("Do it!", on_click()=fire_the_ducks) # bad, passes function returning function
> 
> 
> Would that last case add to the novices' confusion?

Each bad case has a corresponding bad case using lambda,
so I don't think we'd be adding any more badness overall.

>>> And it doesn't use any colons!
> 
> I don't understand the problem with the colons

Some people don't like the idea of colons inside expressions.
Personally I don't mind, as long as it's done tastefully
(e.g. in conjunction with keywords).

> And now, the parsing:
> 
> First, in the grammar (see 6.3.4 Calls), you have to expand the left side of
> keyword_item.

The grammar in the Language Reference is not quite the same
as the grammar used by CPython. The parser actually already
allows a general expession on the left of the =, and then
sorts it out later in the compilation process. So it should
be relaively easy to implement.

> but now at the AST level there's no way
> to distinguish between "key(x)=x.date" and "key=lambda x: x.date". Is that
> acceptable?

Yes, because there isn't meant to be any semantic difference
between them.

-- 
Greg


More information about the Python-ideas mailing list