Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: pass statement in lambda form

A Python newbie question, why is this syntax invalid: lambda: pass, while this: def f(): pass is correct?

Thanks for your insight.

like image 872
Rez Avatar asked Oct 14 '12 14:10

Rez


People also ask

Can lambda expressions contain statements in Python?

In particular, a lambda function has the following characteristics: It can only contain expressions and can't include statements in its body. It is written as a single line of execution.

What is Python lambda function give example?

In Python, a lambda function is a single-line function declared with no name, which can have any number of arguments, but it can only have one expression. Such a function is capable of behaving similarly to a regular function declared using the Python's def keyword.


1 Answers

lambdas can only contain expressions - basically, something that can appear on the right-hand side of an assignment statement. pass is not an expression - it doesn't evaluate to a value, and a = pass is never legal.

Another way of thinking about it is, because lambdas implicitly return the result of their body, lambda: pass is actually equivalent to:

def f():     return pass 

Which doesn't make sense. If you really do need a no-op lambda for some reason, do lambda: None instead.

like image 189
lvc Avatar answered Oct 16 '22 16:10

lvc