Sub topic 10
Tail Calls and Tail-Call Optimization
This chapter assumes you can read Python, know what a stack frame holds, and have seen accumulator-passing style from the previous chapter. You also need to know that CPython raises RecursionError when the stack gets too deep. In this chapter you will learn what makes a call a tail call and what tail-call optimization (TCO) does with one. You will also see which languages actually perform it, and why Python does not.
What a Tail Call Is
A tail call is a function call that is the very last thing a function does before it returns. The caller returns the callee's result unchanged: no arithmetic on it, no cleanup after it, no further statements. A call made in this spot is said to be in tail position.
A tail-recursive function is a recursive function whose recursive calls are all tail calls.
Compare the two versions of summing 1..n:
def sum_to(n):
if n == 0:
return 0
return n + sum_to(n - 1) # NOT a tail call: the + happens after the call returns
def sum_to_tail(n, acc=0):
if n == 0:
return acc
return sum_to_tail(n - 1, acc + n) # tail call: the result is returned as-is
print(sum_to(100)) # 5050
print(sum_to_tail(100)) # 5050In sum_to, the caller must remember n so it can add it once the inner call finishes. Its frame still has work pending. In sum_to_tail, the addition happens before the call, inside the argument acc + n. When the inner call returns, the caller has nothing left to do except pass the value up.
That difference is the whole idea. A caller making a tail call has no pending work, so it has no reason to keep its frame.
How Tail-Call Optimization Works Internally
Tail-call optimization is a compiler or interpreter technique that executes a tail call by reusing (or replacing) the current stack frame instead of pushing a new one. Some language specifications call the guaranteed version proper tail calls or tail-call elimination.
Mechanically, a normal call does roughly this:
- Push a return address and a new frame for the callee.
- Run the callee.
- Pop the callee's frame and resume the caller at the return address.
- The caller then returns, popping its own frame.
For a tail call, steps 3 and 4 do nothing useful. The caller only resumes so that it can return right away. An optimizing implementation instead:
- Evaluates the new arguments.
- Overwrites the current frame's parameters with them (or discards the current frame and builds the callee's frame in its place).
- Jumps to the start of the callee, leaving the original return address in place.
When the callee eventually returns, it returns straight to whoever called the first function. For self-recursion, this turns the recursion into a jump back to the top of the function, which is a loop in machine code. Stack depth stays constant no matter how many calls happen.
TCO is not limited to self-recursion. Any call in tail position can reuse the frame, including a call to a different function. This matters for mutual recursion and for state machines written as functions that call each other. Some implementations handle only the self-recursive case, as the table below shows.
Python Does Not Do It
CPython performs no tail-call optimization. A tail-recursive function grows the stack exactly like a non-tail one:
import inspect
def sum_to_tail(n, acc=0):
if n == 0:
print("frames on stack:", len(inspect.stack()))
return acc
return sum_to_tail(n - 1, acc + n)
print(sum_to_tail(50)) # frames on stack: 52 (51 calls + the module frame), then 5050
try:
sum_to_tail(5000)
except RecursionError as e:
print("RecursionError:", e)Rewriting into accumulator style does not make Python code safe for deep inputs. It only makes the code ready to be converted into a loop, which is the subject of the next chapter.
Guido van Rossum rejected TCO for Python in 2009. His reasons were that it erases frames from tracebacks, that it would push programmers toward a style Python is not designed for, and that Python's dynamic name lookup means the interpreter cannot know until runtime whether return f(x) even calls the same function.
Language Support Differs
Whether you can rely on tail calls depends on whether the language guarantees them or the compiler merely may apply them.
| Language | Tail-call behavior | Can you rely on it? |
|---|---|---|
| Scheme | Proper tail calls required by the standard (R5RS onward), for all tail calls | Yes |
| Lua | Proper tail calls for `return f(args)` | Yes |
| Haskell, OCaml, F#, Erlang/Elixir | Tail calls compiled as jumps; idiomatic loops are written this way | Yes, in practice |
| Scala | `@tailrec` makes the compiler turn self-recursion into a loop, or fail to compile | Self-recursion only |
| Kotlin | `tailrec` modifier, same idea as Scala | Self-recursion only |
| C, C++ | GCC and Clang often optimize at `-O2`, but nothing is promised; Clang offers `[[clang::musttail]]` | Only with compiler-specific attributes |
| JavaScript | ES2015 spec requires proper tail calls in strict mode, but only Safari's engine ships it; V8 (Chrome, Node.js) and SpiderMonkey do not | No, for portable code |
| Java, C#, Go, Rust | No guarantee (the .NET runtime has a tail-call instruction that F# uses, but C# does not emit it) | No |
| Python (CPython) | None | No |
The distinction between a guarantee and an optimization is the key decision criterion. If TCO is only an optimization, your program may work in a release build and crash in a debug build, or break after a compiler upgrade. Code that needs constant stack space should only depend on tail calls where the language promises them or where an annotation like @tailrec or musttail makes the compiler fail loudly when it cannot comply.
Gotchas: Calls That Look Like Tail Calls but Are Not
A call is only in tail position if nothing happens after it. Several common patterns hide pending work.
- Arithmetic or wrapping on the result.
return 1 + f(n - 1),return [x] + f(rest), andreturn not f(n)all do work after the call returns. - Cleanup blocks. A call inside
try/finally, inside awithblock, or (in C++) in a scope with objects whose destructors must run is not a tail call. The cleanup is pending. - Exception handlers. In
try: return f(x) except E: ..., the frame must stay alive to catch the exception. - Short-circuit operators. In
return a or f(x), the call tofis in tail position. Inreturn f(x) or a, it is not, because the result still has to be tested. - Multiple recursion. In
return fib(n - 1) + fib(n - 2), neither call is a tail call. Tree-shaped recursion cannot be made tail-recursive just by moving code around. It needs an explicit stack or a different algorithm. - Implicit returns. In a language that requires an explicit
return, a baref(x)as the last statement is often not a tail call: the function then returnsNone/undefined, notf's result.
Trade-offs of TCO
TCO has costs as well as benefits.
- Debugging. Reused frames vanish from stack traces. A crash deep in a chain of tail calls shows only the last frame, so you lose the path that led there.
- Profiling and introspection. Tools that walk the stack see fewer frames than calls made.
- Hidden fragility. A small edit, such as wrapping the call in logging or a
try, silently turns a tail call into a normal one. In languages without@tailrec-style checks, this can bring back stack overflows on large inputs. - Benefit. Where it is guaranteed, TCO lets you write loops as recursion with O(1) stack space. That makes state machines and recursive algorithms over long inputs safe.
A Python Workaround: Trampolines
Without TCO, you can still run tail-recursive logic in constant stack depth with a trampoline. A trampoline is a loop that repeatedly calls thunks, which are zero-argument functions that represent "the next call to make."
def sum_to_tramp(n, acc=0):
if n == 0:
return acc
return lambda: sum_to_tramp(n - 1, acc + n) # return the next step instead of calling it
def trampoline(result):
while callable(result):
result = result()
return result
print(trampoline(sum_to_tramp(100_000))) # 5000050000Each step returns to the trampoline before the next one starts, so the stack never grows past two frames. Trampolines also handle mutual recursion, because any function can return a thunk for any other. They have two drawbacks. Creating a closure per step makes them slower than a loop. They also break if the real final result is itself callable. For self-recursion in Python, converting directly to a while loop is simpler and faster.
Exercise
Which of these return statements contain a tail call to f? (a) return f(n - 1, acc * n) (b) return f(n - 1) * n (c) return acc if n == 0 else f(n - 1, acc + n) (d) try: return f(n - 1) finally: log(n) (e) return f(n - 1) or default
Show answer
Only (a) and (c). In (a), the multiplication happens before the call, inside the arguments. In (c), the conditional expression is decided before f is called, and f's result is returned unchanged. In (b), the result is multiplied after the call returns. In (d), the finally block must run after the call. In (e), f's result must be tested before the function can return.
Exercise
You write a tail-recursive count_down(n) in Python and it fails with RecursionError at n = 5000. A colleague says "it's tail-recursive, so it should be fine." What is wrong with that claim, and what are two ways to make it work for n = 1,000,000?
Show answer
Tail recursion only saves stack space in implementations that perform tail-call optimization, and CPython does not, so every call still pushes a frame until the recursion limit (about 1000 by default) is hit. One fix is to rewrite the function as a while loop, turning the parameters into loop variables. Another is to run it through a trampoline that returns thunks. Raising the limit with sys.setrecursionlimit is not a reliable fix, because 1,000,000 C-level frames can overflow the real thread stack and crash the interpreter.