[Python-ideas] Thoughts on lambda expressions
Sjoerd Job Postmus
sjoerdjob at sjec.nl
Wed Mar 2 19:46:27 EST 2016
On Wed, Mar 02, 2016 at 07:09:44PM -0500, Ed Minnix wrote:
> Perhaps a better keyword like ``fun`` (in F#, for instance).
>
> Giving ``def`` a new meaning would introduce ambiguities, which would be more trouble than the shorter syntax is worth.
>
> - Ed
>
Out of curiosity, what ambiguities do you see being introduced? Right
now, only
def function_name(foo, bar, baz=None):
pass
and
async def function_name(foo, bar, baz=None):
pass
are parseable, from what I can see. Of course, type hints as well. Based
on that, I can not yet see ambiguities. Am I missing something?
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
)
Which starts looking very javascript-ish to me, so maybe never mind. Not
to mention that the placement of the comma is troublesome. And of course
that now the indent **within** an expression also has meaning.
Now I said javascript, I'm even considering adding extra parenthesis
around the arguments, giving (using the simple sort, again):
sorted(datalist, key=def (x): return x[5])
And adding some type hints
sorted(datalist, key=def (x: List[Int]) -> Int: return x[5])
I myself have learned Haskell before learning Python, so to me the
`lambda` is not esoteric, and I have not considered it as such. However,
I can understand that it would be considered as such by people coming to
Python from other languages such as
* Javascript having `function (foo, bar) { statements }`
* Java having `(foo, bar) -> expression` or `(foo, bar) -> { statements }`.
* C# being basically the same as Java, except for using a `=>` instead
of `->`.
For Java and C# I only did a quick 2-minute research, but it seems that
Java and C# provide anonymous functions, while providing shorthand for
expressions.
Regarding changing it, I would be wary of it if only the syntax changed,
without adding any actual benefits.
Using an existing keyword (such as `def`) has the advantage that the
meaning of currently working code does not change.
More information about the Python-ideas
mailing list