[Python-ideas] Syntax for passing lambdas to functions

Andrew Barnert abarnert at yahoo.com
Thu Feb 27 05:13:05 CET 2014


From: Greg Ewing <greg.ewing at canterbury.ac.nz>
Sent: Wednesday, February 26, 2014 2:16 PM


>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))
>
>> 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.

Yes, the grammar in the reference doesn't document what the first stage of the CPython parser does, but it does document what comes out at the AST level, which is the part that should be the same across implementations, and the first thing that's visible from within the interpreter, right?

But yeah, within the CPython grammar:

    argument: test [comp_for] | test '=' test  # Really [keyword '='] test

>> 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.


Sure, but given that ASTs are exposed for introspection, is it expected that you should be able to distinguish two cases by their ASTs? I could see, say, MacroPy wanting to. (I could also see that not being important enough to care about, of course.)


More information about the Python-ideas mailing list