Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No Multiline Lambda in Python: Why not?

I've heard it said that multiline lambdas can't be added in Python because they would clash syntactically with the other syntax constructs in Python. I was thinking about this on the bus today and realized I couldn't think of a single Python construct that multiline lambdas clash with. Given that I know the language pretty well, this surprised me.

Now, I'm sure Guido had a reason for not including multiline lambdas in the language, but out of curiosity: what's a situation where including a multiline lambda would be ambiguous? Is what I've heard true, or is there some other reason that Python doesn't allow multiline lambdas?

like image 635
Imagist Avatar asked Aug 05 '09 14:08

Imagist


People also ask

Can Python lambda have multiple lines?

No, you cannot write multiple lines lambda in Python. The lambda functions can have only one expression.

Can a lambda have multiple expression?

Lambda functions can only have one expression in their body. Regular functions can have multiple expressions and statements in their body.

What are the limitations of lambda function in Python?

Cons on lambda functions:Lambda functions can have only one expression. Lambda functions cannot have a docstring. Many times lambda functions make code difficult to read. For example, see the blocks of code given below.


2 Answers

Guido van Rossum (the inventor of Python) answers this exact question himself in an old blog post.
Basically, he admits that it's theoretically possible, but that any proposed solution would be un-Pythonic:

"But the complexity of any proposed solution for this puzzle is immense, to me: it requires the parser (or more precisely, the lexer) to be able to switch back and forth between indent-sensitive and indent-insensitive modes, keeping a stack of previous modes and indentation level. Technically that can all be solved (there's already a stack of indentation levels that could be generalized). But none of that takes away my gut feeling that it is all an elaborate Rube Goldberg contraption."

like image 182
Eli Courtwright Avatar answered Sep 19 '22 15:09

Eli Courtwright


Look at the following:

map(multilambda x:       y=x+1       return y    , [1,2,3]) 

Is this a lambda returning (y, [1,2,3]) (thus map only gets one parameter, resulting in an error)? Or does it return y? Or is it a syntax error, because the comma on the new line is misplaced? How would Python know what you want?

Within the parens, indentation doesn't matter to python, so you can't unambiguously work with multilines.

This is just a simple one, there's probably more examples.

like image 42
balpha Avatar answered Sep 21 '22 15:09

balpha