syntax – No Multiline Lambda in Python: Why not?

syntax – 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 its 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 (theres 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 doesnt matter to python, so you cant unambiguously work with multilines.

This is just a simple one, theres probably more examples.

syntax – No Multiline Lambda in Python: Why not?

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 wont accept any assignments though, so youll 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 wont need this.

Example:

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

Leave a Reply

Your email address will not be published.