Sub topic 3
What a Lambda Cannot Do
This chapter assumes you can write functions with def, and that you know lists, tuples, dictionaries and list comprehensions. It also assumes you know default values, *args and **kwargs, and that you have seen the basic lambda syntax from the previous chapter. Here you learn where the lambda form stops, what that costs you, and which workarounds are worth using.
The rule: one expression, nothing else
A lambda body is a single expression. Python evaluates that expression when the function is called and returns its value automatically. The grammar has no place for statements, so none can appear, however you format the code.
An expression produces a value. A statement performs an action and does not produce one. The table shows how common constructs are classified.
| Construct | Kind | Allowed in a lambda body? |
|---|---|---|
| `a + b`, `f(x)`, `x[0]` | expression | yes |
| `x if cond else y` | expression | yes |
| `[n * 2 for n in xs]` | expression | yes |
| `(y := x * 2)` | expression (needs parentheses) | yes |
| `return x` | statement | no |
| `y = x * 2` | statement | no |
| `if cond: ...` (block form) | statement | no |
| `for` and `while` loops | statement | no |
| `try` / `except`, `with` | statement | no |
| `raise`, `assert`, `del`, `import`, `pass` | statement | no |
Trying to use a statement is a syntax error, found when Python compiles your code, before anything runs:
try:
compile("lambda x: return x + 1", "<demo>", "eval")
except SyntaxError as exc:
print("SyntaxError:", exc.msg) # the exact wording depends on the Python versionYou never write return in a lambda. The value of the expression is the return value.
Working within the limit
Most lambda restrictions have a small expression-level workaround. Each one has a point where the workaround becomes harder to read than a def.
Branching
The conditional expression replaces if/else. You can chain it for more than two cases:
grade = lambda score: "A" if score >= 90 else "B" if score >= 80 else "C"
print(grade(95), grade(85), grade(50)) # A B CTwo branches read fine. With three or more, a def with if/elif is clearer.
Loops
A comprehension or a generator expression replaces a loop, and it works inside a lambda:
squares_up_to = lambda n: [i * i for i in range(n)]
print(squares_up_to(4)) # [0, 1, 4, 9]Raising errors
raise is a statement, so a lambda cannot contain it. The usual workaround is a small helper function that raises:
def fail(exc):
raise exc
parse = lambda s: int(s) if s.isdigit() else fail(ValueError(f"bad number: {s!r}"))
print(parse("42")) # 42
try:
parse("4x2")
except ValueError as exc:
print(exc) # bad number: '4x2'The helper works, but it moves the interesting behavior out of the lambda. When you need this trick, a plain def parse(s): ... with raise inside is usually the better design.
Handling exceptions
There is no expression form of try/except. If a callback must recover from errors, write a named function:
def safe_int(text, default=0):
try:
return int(text)
except ValueError:
return default
print(list(map(safe_int, ["1", "x", "3"]))) # [1, 0, 3]Assignment
A lambda cannot contain name = value. The walrus operator := is an assignment expression, and it is allowed when you wrap it in parentheses. The name it binds is local to the lambda:
total_with_tax = lambda price: (taxed := price * 1.2) and round(taxed, 2)
print(total_with_tax(10)) # 12.0This trick is rarely worth it. If you need an intermediate name, that is a sign the logic wants a def.
Side effects
Calls such as print(...) or items.append(...) are expressions, so they run inside a lambda. Calling print in a lambda is normal. Using a lambda only for its side effects, for example inside map that you never read, hides the intent and is best avoided. Note also that map is lazy, so nothing runs until something consumes the result.
What a lambda can accept
The limit applies to the body only. The parameter list supports the same features as def: defaults, *args, keyword-only parameters, **kwargs and positional-only parameters.
scale = lambda x, *, factor=2, **extra: x * factor
print(scale(5)) # 10
print(scale(5, factor=3)) # 15What you cannot add is a type annotation. The syntax lambda x: int: x does not parse, because the colon after the parameters ends the parameter list. You also cannot give a lambda a docstring, because a docstring is a statement-position string literal at the top of a body.
Identity and debugging costs
A lambda has no name of its own. Every lambda reports the same name:
f = lambda x: 1 / x
def g(x):
return 1 / x
print(f.__name__) # <lambda>
print(g.__name__) # gThis has practical effects:
- Tracebacks show
<lambda>for the frame, so when several lambdas are in the call chain you must rely on line numbers to tell them apart. - Log messages and
reproutput are less informative, because they cannot name the function. - Decorators that use
func.__name__, such as thelog_callsdecorator you will see later in this tutorial, print<lambda>. - Profilers group all lambdas by file and line, which is rarely what you want.
The line f = lambda x: ... makes this worse, because you give the function a variable name but not a function name. PEP 8 recommends against it (linters report it as E731). If a function needs a name, use def, which sets __name__ and makes the traceback readable. Using a lambda directly as an argument, such as key=lambda p: p[1], is the case it was designed for.
Pickling and other tools that need names
Python's pickle module saves functions by storing their module and name, then looks them up again when loading. A lambda has no usable name, so pickling fails. This matters because multiprocessing pickles the functions you send to worker processes.
import pickle
def double(x):
return x * 2
print(len(pickle.dumps(double)) > 0) # True
try:
pickle.dumps(lambda x: x * 2)
except (pickle.PicklingError, AttributeError) as exc:
print("cannot pickle a lambda:", type(exc).__name__)The exact exception type depends on the Python version. If you pass work to a process pool, use module-level def functions, or objects from functools.partial and operator, which can be pickled when the function inside them can.
Deciding when you have hit the limit
Use this checklist while writing a lambda. Any "yes" answer is a signal to switch to def.
A related guideline: if you must explain what a lambda does in a comment, the function deserves a name and a docstring.
Common mistakes
- Writing
returninside a lambda. This is a syntax error. Removereturn. - Putting a block
iforforin the body. Use a conditional expression or a comprehension, or switch todef. - Using
=to assign. This is a syntax error. Use:=in parentheses only if you really need it. - Printing in
mapand expecting it to run.mapreturns a lazy iterator, so nothing happens until you consume it. - Nesting lambdas to simulate multiple statements. A lambda returning a lambda returning a tuple of calls compiles, but nobody can maintain it.
Exercise
This code is meant to convert strings to integers and return -1 for bad input, but it does not compile. Why, and how would you fix it? convert = lambda s: try: return int(s) except ValueError: return -1
Show answer
The lambda body contains the statements try, except and return, which a lambda cannot hold because its body must be one expression. Replace it with a def: def convert(s): try: return int(s) except ValueError: return -1 This version also gets a real name for tracebacks, and you can add a docstring and annotations. If you still want an inline expression, you could write lambda s: int(s) if s.isdigit() else -1, but that treats inputs like "-5" differently, so the def is safer.
Exercise
Why does multiprocessing.Pool().map(lambda x: x + 1, [1, 2, 3]) fail, and what is the smallest change that makes it work?
Show answer
multiprocessing pickles the function to send it to worker processes, and pickle looks functions up by module and name. A lambda's name is <lambda>, so the lookup fails. Define a module-level function with def addone(x): return x + 1 and pass addone instead, or use functools.partial(operator.add, 1), which is picklable.