No Multiline Lambda in Python: Why not? No Multiline Lambda in Python: Why not? python python

No Multiline Lambda in Python: Why not?


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."


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.


This is generally very ugly (but sometimes the alternatives are even more ugly), so a workaround is to make a braces expression:

lambda: (    doFoo('abc'),    doBar(123),    doBaz())

It won't accept any assignments though, so you'll have to prepare data beforehand.The place I found this useful is the PySide wrapper, where you sometimes have short callbacks. Writing additional member functions would be even more ugly. Normally you won't need this.

Example:

pushButtonShowDialog.clicked.connect(    lambda: (    field1.clear(),    spinBox1.setValue(0),    diag.show())