On 23.02.2021 15:29, Paul Moore wrote:
On Tue, 23 Feb 2021 at 14:10, M.-A. Lemburg
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 -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Experts (#1, Feb 23 2021)
Python Projects, Coaching and Support ... https://www.egenix.com/ Python Product Development ... https://consulting.egenix.com/
::: We implement business ideas - efficiently in both time and costs ::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 https://www.egenix.com/company/contact/ https://www.malemburg.com/