Python Lambda – Why Python Doesn’t Allow Multi-Line Lambdas

lambdapython

Can someone explain the concrete reasons why BDFL choose to make Python lambdas single line?

This is good:

lambda x: x**x

This results in an error:

lambda x:
    x**x

I understand that making lambda multi-line would somehow "disturb" the normal indentation rules and would require adding more exceptions, but isn't that worth the benefits?

Look at JavaScript, for example. How can one live without those anonymous functions? They're indispensable. Don't Pythonistas want to get rid of having to name every multi-line function just to pass it as an argument?

Best Answer

Guido van van Rossum answered it himself:

But such solutions often lack "Pythonicity" -- that elusive trait of a good Python feature. It's impossible to express Pythonicity as a hard constraint. Even the Zen of Python doesn't translate into a simple test of Pythonicity...

In the example above, it's easy to find the Achilles heel of the proposed solution: the double colon, while indeed syntactically unambiguous (one of the "puzzle constraints"), is completely arbitrary and doesn't resemble anything else in Python...

But I'm rejecting that too, because in the end (and this is where I admit to unintentionally misleading the submitter) I find any solution unacceptable that embeds an indentation-based block in the middle of an expression. Since I find alternative syntax for statement grouping (e.g. braces or begin/end keywords) equally unacceptable, this pretty much makes a multi-line lambda an unsolvable puzzle.

http://www.artima.com/weblogs/viewpost.jsp?thread=147358

Basically, he says that although a solution is possible, it's not congruent with how Python is.

Related Topic