On Tue, 23 Feb 2021 at 15:52, M.-A. Lemburg <m...@egenix.com> wrote:
>
> On 23.02.2021 15:29, Paul Moore wrote:
> > On Tue, 23 Feb 2021 at 14:10, M.-A. Lemburg <m...@egenix.com> wrote:
> >>
> >> The natural way in Python to write an anonymous function would
> >> be to simply drop the name in a regular function definition:
> >>
> >> def (a): return a**2
> >>
> >> The lambda notation is less verbose and closer to computer
> >> science theory, though:
> >>
> >> lambda a: a**2
> >>
> >> FWIW: I don't understand why people are so unhappy with lambdas.
> >> There isn't all that much use for lambdas in Python anyway. Most
> >> of the time, a named function will result in more readable code.
> >
> > Typically because they are simple expressions like the a**2 you used above.
> >
> > def a_squared(a):
> >     return a**2
> >
> > is way over the top.
>
> Fair enough. Although as soon as you use the same such function
> more than once in your application, giving it a name does make
> sense :-)
>
> > Thinking about it, maybe the *real* solution here is to use one of the
> > "placeholder variable" libraries on PyPI - there's "placeholder" which
> > I found on a quick search:
> >
> >     from placeholder import _     # single underscore
> >
> >     _.age < 18     # lambda obj: obj.age < 18
> >     _[key] ** 2    # lambda obj: obj[key] ** 2
> >
> > Some people will hate this sort of thing - probably the same people
> > who can't see why anyone has a problem with lambda - but it doesn't
> > need a language change, and it's available now.
> >
> > I guess I've convinced myself here - we already have shorter
> > alternatives to lambda, so why add a new built-in one?
>
> People should have a look at the operator module. It's full of
> short (and fast) functions for many things you often write
> lambdas for:
>
> https://docs.python.org/3/library/operator.html

Definitely. But in cases like this (where brevity and matching the
form of an expression is considered important) `partial(add, 2)`
doesn't really compare to `lambda x: x+2` (or `x -> x+2`, or `_+2` if
you like placeholders). And even using functools.partial, the operator
module won't be able to replace `lambda x: x*x` (you can't even
transform it to `x**2` and use partial, because the constant is the
right hand argument).

It's all very subjective, of course.

Paul
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/QHFAJGNSV5FMOAF52SDBQ4EN3MY6LJG2/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to