[Python-ideas] Thoughts on lambda expressions

Sjoerd Job Postmus sjoerdjob at sjec.nl
Wed Mar 2 20:41:36 EST 2016


On Thu, Mar 03, 2016 at 12:20:41PM +1100, Chris Angelico wrote:
> On Thu, Mar 3, 2016 at 11:46 AM, Sjoerd Job Postmus <sjoerdjob at sjec.nl> wrote:
> > One thing I do see as being different, is that `def` takes statements,
> > not an expression. So, one should write an extra `return` as in
> >
> >     sorted(datalist, key=def x: return x[5])
> >
> > (Not requiring `return` here would be very confusing if one were to
> > re-use the keyword `def`.)
> >
> > On the other hand, then one might even do something like
> >
> >     sock.send_data(data,
> >         on_error=def err:
> >             some
> >             statements
> >             handling
> >             err
> >         ,
> >         on_complete=def:
> >             draw
> >             a
> >             kitten
> >     )
> >
> 
> Someone will correct me if I'm wrong, but I'm pretty sure Python's
> grammar cannot handle statements inside expressions. Creating a "def"
> expression that has a suite inside it would mess with everyone's heads
> AND the parser, and I'm pretty sure that one won't fly.
 
I would be very surprised if the current grammar would be able to handle
it. After all, it (rightfully) can't handle an assignment inside an
expression either---like `if x = foo():`.

I'm uncertain as to whether or not the grammar would be (easily)
tweakable to allow a `def` suite inside an expression. I'm not familiar
enough with the grammar (yet).

As for messing with everyone's heads, I'm not worried about that too
much yet. I think the example I gave does not look too bad (it somewhat
follows Javascript idioms, though, and is thus not Pythonic).

Now that Python has gotten async functions, it might very well be used
even more for callback based programming. To me, that reminds me of
Javascript, where inline definition of callbacks is the norm, not the
exception. I'm not claiming that Python idioms in this regard can (or
should or will) change in that direction, however I see that Java,
Javascript, Ruby, C# (and possibly other languages as well) offer inline
definition of multi-statement callbacks.

Anyhow, this is completely off-topic, as the topic is about changing the
syntax of a simple lambda, not on enabling multi-statement inline
function definitions. So, unless somebody gets enthuasiastic enough to
fork the thread off, I'll let it rest.


More information about the Python-ideas mailing list