Tom Ritchford
1 min readJul 30, 2021

--

I disagree with the "clearer" part - and so does flake8, the standard Python style tool, so I'm not alone in that.

A function definition would have been clearer here, both I and flake8 think.

I've been programming in Python for 17 years now. I really thought I would use lambdas more (I do use them of course) but unfortunately, they hit an unsweet spot.

1. They can only be one line long

This is the showstopper. If I put in a lambda now, almost certainly during maintenance I'll need to add more logic or a condition and change it to a stand-alone function.

Two beginner issues:

2. The syntax is different from function definitions.

3. The lambda name is unintuitive.

Before you yell at that one, I have actually studied the lambda calculus, and long before I hit Python — but it always seems to perturb beginners.

And one more subtle issue: what does this code fragment do?

fs = [(lambda: i) for i in range(8)]
print(*(f() for f in fs))

4. lambda's capture by reference leads to subtle mistakes.

Don't get me wrong, you can make this mistakes with def almost as easily - but it's a bit easier to do with a lambda.

Thanks for a fun article!

--

--

No responses yet