Python: pass statement in lambda form

Rez picture Rez · Oct 14, 2012 · Viewed 13.8k times · Source

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

Thanks for your insight.

Answer

lvc picture lvc · Oct 14, 2012

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.