0

I've found this page:

http://effbot.org/pyfaq/why-can-t-lambda-forms-contain-statements.htm

Nevertheless, it's not so clear the reason why. Lambdas are powerful, and, in my mind, they would be much more if it was possible to use statements/assignments inside their scope.

For example:

y = 0
f = lambda x: y = 5, x+y # Statements first, expression later.
print f(5) # 10

Someone must have considered this, and there must be a reason why it's not implemented (Perhaps to avoid using them too much instead of a trivial def?).

Ericson Willians
  • 7,606
  • 11
  • 63
  • 114
  • 2
    Why not `lambda x: x + 5`? Also, possible duplicate of http://stackoverflow.com/questions/1233448/no-multiline-lambda-in-python-why-not – jayelm May 24 '14 at 07:27
  • 1
    @JesseMu: Although I wouldn't say an exact duplicate, the second answer there is, what I believe the OP is looking for. – Dair May 24 '14 at 07:29
  • 1
    Because it makes readability worse. Also giving names to anonymous functions kinda defeats the point. – John La Rooy May 24 '14 at 07:36

2 Answers2

3

First one needs to understand that the lambda construct creates an expression that evaluates to the created function. This is very different from a def, which is a statement, and works by side effect of binding the created function to the specified name. For lambda to be useful at all, it must be an expression, otherwise you couldn't nest it in other expressions.

As the linked FAQ explains, no other Python expression is allowed to nest statements. This is because the core syntactic tradeoffs of the Python language preclude such possibility, as persuasively argued by Guido. Since there is a very easy workaround, i.e. using a def, it was deemed not worthwhile to warp the syntax of the language to accomodate statements in lambda.

Also note that lambda is not the only place in the language that requires an expression. You can't put a statement in the test of an if or while, nor in the expression required by the for statement. Yet this is considered a good thing - if you need statements there, simply extract them into a function and call it. Exactly the same applies to lambda.

user4815162342
  • 141,790
  • 18
  • 296
  • 355
0

What is the different between:

f = lambda x: y = 5; x+y

and

def f(x):
    y = 5
    return x+y

?

The later is more readable, it has a consistent syntax and the only code you have to write more, than with your lambda-definition is the return. So there is no need in what you suggest but only more complicated rules.

Daniel
  • 42,087
  • 4
  • 55
  • 81