53

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

Thanks for your insight.

Rez
  • 615
  • 1
  • 6
  • 9

4 Answers4

53

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.

Lee Netherton
  • 21,347
  • 12
  • 68
  • 102
lvc
  • 34,233
  • 10
  • 73
  • 98
  • 3
    That makes sense, thanks! But then, since `lambda: None` still returns a value, is there any way I can define an anonymous function that behaves exactly like `def f(): pass`? – Rez Oct 14 '12 at 14:32
  • 22
    @Rez it *is* actually the same - all Python functions return a value; if they fall off the end, or reach a bare `return`, they return `None`. – lvc Oct 14 '12 at 14:39
49

That is an error because after the colon you have to put the return value, so:

lambda: pass

is equal to:

def f():
   return pass

that indeed makes no sense and produces a SyntaxError as well.

etuardu
  • 5,066
  • 3
  • 46
  • 58
30

The return value of a function without a return statement is None. You can see this from the simple pass function that is defined in the OP:

>>> def f():
...     pass
... 
>>> print f()
None

If you are looking for a lambda function that is equivalent to this "no-op" function, then you can use:

lambda: None

For example:

>>> f = lambda: None
>>> print f()
None
Lee Netherton
  • 21,347
  • 12
  • 68
  • 102
0

If you want to use a lambda you could rely on the Ellipsis literal ....

Your lambda would become lambda: ....

The Ellipsis literal is often used instead of pass.

darkheir
  • 8,844
  • 6
  • 45
  • 66