r/Python • Python Morsels • Sep 27 '18

Stop writing lambda expressions in Python

http://treyhunner.com/2018/09/stop-writing-lambda-expressions/
0 Upvotes

26 comments sorted by

30

u/Nicksil Sep 27 '18 edited Sep 27 '18

Title states to stop using lambda, the article states to use lambda when necessary.

I knew it was click bait going in, but I always hold out some hope.

5

u/treyhunner Python Morsels Sep 27 '18

I considered this before publishing, but I've been sitting on this for days now and couldn't think up a more appropriate title. Do you think "Stop overusing lambda expressions in Python" would have been more appropriate?

6

u/rcfox Sep 27 '18 edited Sep 27 '18

Tuple unpacking can improve readability over using hard-coded index lookups. Using lambda expressions often means sacrificing some Python language features, specifically those that require multiple lines of code (like an extra assignment statement).

Rebuttal: points_by_color = sorted(points, key=lambda ((x, y), color): color)

Overall agree though.

Edit: Looks like tuple parameter unpacking was removed in Python 3. https://www.python.org/dev/peps/pep-3113/ (I'm still using 2.7 for work, so that's my default.)

3

u/Vaphell Sep 27 '18

Looks like tuple parameter unpacking was removed in Python 3

I am still a bit salty about this in the context of lambdas. indexing into tuples as opposed to unpacking is bullshit and the supposedly more elegant itemgetter whatever is bullshit too.

1

u/treyhunner Python Morsels Sep 27 '18

Yes that was removed in Python 3. I feel like that syntax was actually particularly confusing with lambda expressions though.

When I first glanced at that code I assumed a dictionary was involved somehow or maybe incorrect syntax because my brain didn't parse the tuples before the `:` as arguments.

This may be because I'm not used to seeing/using tuple unpacking in lambda expressions (and never really saw it used in traditional `def`-defined functions either).

3

u/rcfox Sep 27 '18

I think the parameter unpacking is quite nice if you think of it as a limited form of pattern matching. I can definitely understand why they removed it from the language though.

2

u/Vaphell Sep 27 '18 edited Sep 27 '18

This may be because I'm not used to seeing/using tuple unpacking in lambda expressions (and never really saw it used in traditional def-defined functions either).

I am guessing this is the reason. If you had to write something seemingly trivial, like sorting x, y points a few times, the old syntax is simply better compared to the new fallback. Traditional defs are whatever, you can always unpack by hand because you are not limited to signature and 1 expression.

in case of lambdas it is a significant loss of expressiveness.

given an admittedly somewhat byzantine example with (point, color) structures compare let's say

lambda ((x, y)(r, g, b)): (g, x)

to equivalent

lambda t:  t[1][1], t[0][0]

the latter tells you literally nothing of value about what you are looking at and goes against everything python stands for. Everywhere else you unpack the shit out of everything in order to avoid indices all over the place and to have meaningful, descriptive vars, not so much here.

I am of an opinion that unpacking should have been special-cased for lambdas or some special syntax should be put in place to achieve similar effect.

1

u/Sporke Sep 27 '18

I was hoping the author would mention operator.itemgetter(1) in that case

1

u/__deerlord__ Sep 27 '18

Can you explain whats going on with this lamda? Same as

def f(t, color):

where t is the 2-tuple (x,y)?

1

u/rcfox Sep 27 '18

No, it would be the same as:

def f(point):
    (x, y), color = point
    return color

points is a list of tuples, and the key function only takes a single argument. Python 2.7 allows you to unpack an iterable in the place of a parameter.

2

u/__deerlord__ Sep 27 '18

Is it a list of 2-tuples? Can you provide an example of what point is, and then what it unpacks to for (x,y), color?

Because the following works on py3

c = [(1,2), (3,4)]
(x,y), color = c
x
>>> 1
y
>>> 2
color
>>> (3,4)

1

u/rcfox Sep 27 '18

From the article: points = [((1, 2), 'red'), ((3, 4), 'green')]

The thing that doesn't work in Python 3 is unpacking in the parameter list. ie:

def foo(((x, y), color)): 
   return color

colors = map(foo, points)

The above does work in Python 2.7 but not Python 3.

1

u/__deerlord__ Sep 28 '18

It sounds like this implicitly uses *args, but that in python3 you can use itertools.starmap for this. Explicit > implicit.

Note: I havent played with this, though, too late here.

3

u/AN3223 Sep 27 '18

Lambdas become a lot less relevant when currying and function composition are used. Since Python doesn't have great facilities for these, lambdas are often the next thing.

2

u/david2ndaccount Sep 27 '18

The real reason to not use lambdas in python is that they’re arbitrarily crippled. Also, why are they lambda and not def? Why don’t they support names? etc., etc. Guido just crippled them and it really makes Python worse for it.

1

u/billsil Sep 28 '18

Guido didn't write lambda. He accepted a patch. Guido didn't know how you'd want to use it in 1991.

4

u/david2ndaccount Sep 28 '18

He has systematically rejected all proposals for improving it.

1

u/billsil Sep 28 '18

Lambdas are still bad...

1

u/Aeon_Mortuum Snake Oil Sep 28 '18

Is there actually a reason why lambda can't have a block-level type syntax instead of just being inline, limited to a single expression? Like in JavaScript arrow functions:

() => {

statement 1;

statement 2;

...

}

I'm not sure if there is something in the language that would make it really difficult or impossible to implement, or Guido was just against it (and also, now that Guido is not the BDFL any longer, could there be a change of vision with regards to how some of these things are perceived and what should and shouldn't make it into the language?)

1

u/david2ndaccount Sep 28 '18

Curly brackets are already used for set/dict literals so you can’t use that (a theoretical improved lambda should allow for returning a dict literal without having to use double brackets). Python blocks are purely whitespace based, but whitespace is ignored in the middle of brackets, like for a function call. So you need a syntax for blocks that isn’t white-space based and doesn’t look too different from normal python.

3

u/Axxhelairon Sep 27 '18

i never buy into the idea that you shouldnt use something slightly unconventional because others might not understand it when its a core part of the language, dinosaur regressive thinking like this would stop anyone from using completely basic languages features like tuple destructuring, * unpacking, decorators, ** kwargs unpacking, partial function applicators, etc because you're too scared to learn something new

id say dont use lambdas for anything complex because they're a half baked implementation and are restricted to being expression bodies and fitting things in one line makes it actually unreadable, id just think you're being stubborn if lamda a, b: a * b takes you more than two minutes to figure out without even knowing what a lamda is or think that its hard to understand

3

u/etrnloptimist Sep 27 '18

I agree. Used in this way, lambdas heavily promote a functional style to writing Python code. It is really opposite of the style and spirit of Python. Python is an imperative language, not a functional one. It is no secret that Guido strongly dislikes functional style. And if that opinion is good enough for Guido, it is good enough for me.

1

u/galuszkak Sep 28 '18

I overall agree with Trey Hunner, but I think the root of problem is that, we don't think what we can do to improve lambdas.

One of the pain point of Python lambdas is that they are single line thing. It's bad in my view (I know author said that this doesn't matter to him). I just love lambdas construct in kotlin. They are supper elegant, easy and having default parameter it is so convenient so constructs like ints.filter { it > 0 } are so much more readable, short and easy to understand.

Maybe we should revise lambda syntax and propose PEP which is less verbose and more elastic? Kotlin got it just more than right and I would just love to have similar syntax in Python, I have some concepts in my mind's, but maybe some people have better ideas?

Overall experience to use more functional oriented paradigm in Python would be improved a lot.

0

u/[deleted] Sep 27 '18

[deleted]

6

u/treyhunner Python Morsels Sep 27 '18

"No true Python programmer..."

People can and do use Python for years without understanding all its features. I certainly don't have all the built-ins memorized and I'd be surprised if I had all the syntax memorized as well.

6

u/Python4fun Java4work Sep 27 '18

Raymond Hettinger even admitted that he has to open python and tinker for a minute when he is working with different bits. He doesn't have everything memorized

1

u/billsil Sep 28 '18

Not true. Guido accepted a patch.