Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda and multiple statements in Python

Tags:

python

lambda

Can anyone explaine that behavior of lambda functions?

import sys
X = lambda: sys.stdout.write('first');sys.stdout.write("second")
X()

Returns: -> secondfirst

And one more problem:

lambda: sys.stdout.write("...");sys.exit(0) 

Or

lambda: sys.exit(0);sys.stdout.write("...")

Doesn't execute correctly. And one more question, why in first primer execution flow goes from right to left?

Trying with: Python3+(3.4, 3.2) OS: Linux (Ubuntu), OSX

like image 871
user4549992 Avatar asked Feb 10 '15 10:02

user4549992


People also ask

Can Python lambda have multiple statements?

Lambda functions does not allow multiple statements, however, we can create two lambda functions and then call the other lambda function as a parameter to the first function.

Can lambda expressions contain multiple statements?

In particular, a lambda function has the following characteristics: It can only contain expressions and can't include statements in its body.


1 Answers

The syntax for lambda is:

lambda <args>: <expression>

where <expression> must be a single expression. It cannot be a statement, or multiple statements, or multiple expressions separated by ;.

What happens in your code is that lambda has higher priority over ;, so that gets parsed as: X = lambda: sys.stdout.write('first') followed by sys.stdout.write("second"). Adding parentheses around sys.stdout.write('first') ; sys.stdout.write("second") would not work and produce a syntax error.

My trick to do multiple things inside a lambda is:

f = lambda: [None, sys.stdout.write('first'), sys.stdout.write("second")][0]

and the other one:

f = lambda: [None, sys.stdout.write("..."), sys.exit(0)][0]

However that kind of defeats the purpose of a lambda function, which is to do something short and really simple.

I guess that would still be OK in your specific example, but kind of looks like a hack.

like image 194
fferri Avatar answered Oct 19 '22 02:10

fferri