Sub topic 3
What a lambda cannot do
This chapter assumes you can write a basic lambda and use def with default arguments. It covers what a lambda body may contain, what happens when you go past that limit, and how to recognize when to switch to def.
One expression, nothing else
A lambda body is a single expression. An expression produces a value, such as x * 2, a if c else b or f(x). The value is returned automatically, and there is no return keyword.
Python statements are not expressions, so they cannot appear in a lambda. The excluded statements include:
- assignment with
=or+= return,raise,assert,delandpassimportforandwhileloopstryandwithblocksifas a statement (the conditional expression is allowed)
Using one is a syntax error, found when the code is compiled:
try:
compile("lambda x: y = x", "<example>", "eval")
except SyntaxError:
print("SyntaxError: assignment is a statement")What you can still do
Many things that look like statements have an expression form:
| You want | Use in a lambda |
|---|---|
| `if` / `else` | `a if cond else b` |
| A loop that builds a list | a comprehension, `[f(n) for n in xs]` |
| Several conditions | `and`, `or`, `not`, chained comparisons |
| Assignment inside an expression | the walrus operator, `(y := x * 2)` |
| Calling a method | `s.strip().lower()` |
sign = lambda n: "negative" if n < 0 else "non-negative"
print(sign(-4)) # negative
print(sign(0)) # non-negativeThese tricks have a cost. A lambda with nested conditional expressions or a walrus is harder to read than the same logic in a def. If you need them, that is usually a sign to write a function.
No annotations, no docstring, no name
A lambda has no place for a docstring. It also cannot carry parameter or return annotations, because the syntax has no slot for them. Its __name__ is always <lambda>:
square = lambda x: x * x
print(square.__name__) # <lambda>
def square_def(x):
return x * x
print(square_def.__name__) # square_defAssigning a lambda to a name does not change its __name__. PEP 8 recommends against name = lambda ... for this reason, and linters report it as E731. If a function deserves a name, use def.
The missing name also hurts debugging. A traceback shows <lambda> for every failing lambda, so you cannot tell which one failed:
ratios = [lambda a, b: a / b, lambda a, b: a // b]
print(ratios[0](6, 3)) # 2.0
ratios[1](6, 0) # ZeroDivisionError, reported in "<lambda>"Where the limit shows up
flowchart TDThe diagram below is the check to run when a lambda starts to grow.
A common case is error handling. A lambda cannot contain try, so a conversion that may fail needs a def:
def to_int_or_zero(text):
try:
return int(text)
except ValueError:
return 0
values = ["4", "x", "7"]
print(list(map(to_int_or_zero, values))) # [4, 0, 7]The named function is also easier to test on its own.
Exercise
Which of these is a valid lambda, and why are the others not? (a) lambda x: return x + 1 (b) lambda x: x + 1 if x > 0 else 0 (c) lambda x: total += x
Show answer
Only (b) is valid. It is a single expression that uses a conditional expression. (a) uses return, which is a statement. (c) uses augmented assignment, which is also a statement. For (a), drop return and write lambda x: x + 1. For (c), write a def.
Exercise
A lambda assigned to parse fails inside a larger program. What does the traceback call the function, and what change would give it a useful name?
Show answer
The traceback calls it <lambda>. Rewriting it with def parse(...) gives the function the name parse, which then appears in the traceback.