Sub topic 17
Tail Recursion and Tail-Call Optimization
This chapter assumes you already know how the call stack stores one frame per active call. It also assumes you have seen CPython raise RecursionError when recursion gets too deep, as the previous chapter showed. Here we look at a specific shape of recursive function, the tail-recursive form. In some languages this shape runs in constant stack space. In Python it does not.
What a Tail Call Is
A call is in tail position when it is the very last thing a function does before it returns. Nothing happens to the call's result except handing it straight back to the caller. A function is tail recursive when every recursive call it makes is in tail position.
Compare the two factorial functions below.
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
def factorial_acc(n, acc=1):
if n == 0:
return acc
return factorial_acc(n - 1, acc * n)
print(factorial(5)) # 120
print(factorial_acc(5)) # 120In factorial, the recursive call is not the last action. After factorial(n - 1) returns, the frame still has to multiply the result by n. So the frame must stay alive and keep n around while it waits.
In factorial_acc, the multiplication happens before the call, inside the argument acc * n. When the recursive call returns, its value goes straight up to the caller unchanged. The current frame has nothing left to do.
The Accumulator Pattern
The extra parameter acc is an accumulator. It carries the partial result down through the calls, so no work has to be done on the way back up. Converting a function to tail form usually means finding what each frame would have done after the call and moving that work into an accumulator argument instead.
What Tail-Call Optimization Does
If a frame has nothing left to do after a tail call, the frame is no longer needed. Tail-call optimization (TCO) is a technique where the compiler or interpreter reuses the current frame for the tail call, or replaces it, instead of pushing a new one on top. The stack then stays the same size no matter how many calls happen, and the recursion behaves like a loop.
Languages differ in whether they provide TCO.
| Language or tool | Tail-call behavior |
|---|---|
| Scheme | Proper tail calls are required by the language standard |
| Scala | `@tailrec` makes the compiler confirm that self-recursion becomes a loop, and the build fails if it cannot |
| Kotlin | The `tailrec` modifier compiles self-recursion into a loop |
| C and C++ | Optimizing compilers often do it, but the language does not guarantee it |
| JavaScript | ES2015 specifies it, but in practice only Safari implements it |
| CPython | Never performs it |
Why CPython Does Not Optimize Tail Calls
Python's designers left TCO out on purpose. Reusing frames would erase them from tracebacks, so an error deep in a chain of calls would show fewer frames than really ran. Python also treats readable stack traces and a simple execution model as more important than this optimization. The practical result is that a tail-recursive Python function still uses one frame per call.
import sys
def factorial_acc(n, acc=1):
if n == 0:
return acc
return factorial_acc(n - 1, acc * n)
print(sys.getrecursionlimit()) # often 1000
try:
factorial_acc(5000)
except RecursionError as e:
print("RecursionError:", e)Turning a Tail Call into a Loop by Hand
Tail recursion is still useful in Python, because a tail-recursive function converts mechanically into a while loop:
- Wrap the body in
while True:. - Leave the base case as a
return. - Replace the recursive call with reassignment of the parameters to the new argument values.
def factorial_loop(n):
acc = 1
while True:
if n == 0:
return acc
n, acc = n - 1, acc * n
print(factorial_loop(5)) # 120
print(len(str(factorial_loop(5000)))) # 16326 digits, no RecursionErrorThe tuple assignment n, acc = n - 1, acc * n matters. It computes both new values from the old ones before assigning either one. If you write two separate assignments, n = n - 1 followed by acc = acc * n, the second line uses the already-updated n and gives the wrong answer.
A Trampoline: TCO Emulated in Python
A trampoline is a small driver loop that lets tail-recursive code run without growing the stack. Instead of making the tail call, the function returns a zero-argument function (a thunk) that would make the call. The trampoline keeps calling thunks until it gets a value that is not callable.
def trampoline(f, *args):
result = f(*args)
while callable(result):
result = result()
return result
def fact_t(n, acc=1):
if n == 0:
return acc
return lambda: fact_t(n - 1, acc * n)
print(trampoline(fact_t, 5)) # 120
print(len(str(trampoline(fact_t, 5000)))) # 16326Each thunk runs and returns before the next one starts, so the stack depth stays at about two frames. Trampolines also handle mutual tail calls. The is_even and is_odd pair from the Mutual Recursion chapter could return thunks in the same way. The costs are a closure allocation on every step and a rule that the real result must never be a callable value, because the trampoline would call it.
Common Mistakes
- Treating a call that appears on the
returnline as a tail call. Inreturn 1 + f(n - 1)andreturn f(n - 1) * n, work still happens afterfreturns, so neither call is in tail position. - Assuming tail form is safe in Python. It is not, as the
RecursionErrorexample above shows. - Placing a call inside
try/finallyorwith. The cleanup code runs after the call returns, so the call is not in tail position, even in languages that perform TCO. - Having two recursive calls. Tree recursion such as naive
fibcannot make both calls tail calls. Only one call can be last. Such functions need an explicit stack, which the next chapter covers. - Updating loop variables in sequence during manual conversion. Use simultaneous (tuple) assignment, as shown above.
When the Tail Form Is Worth It
Use tail recursion directly when your language guarantees TCO, such as Scheme, or Scala and Kotlin with their annotations. In Python, treat the tail form as a stepping stone. It is a clear way to design the logic, and it turns straight into a loop when inputs can be deep. For non-tail recursion that cannot easily use an accumulator, such as tree traversal, use an explicit stack.
Exercise
Is the recursive call in return helper(n - 1) + 0 in tail position? Explain.
Show answer
No. After helper(n - 1) returns, the function still has to add 0 to the result. Because work remains after the call, the frame must stay alive, so this is not a tail call, even though adding 0 changes nothing.
Exercise
Rewrite total(items), which returns items[0] + total(items[1:]), as a tail-recursive function with an accumulator. Then convert it into a while loop.
Show answer
Tail-recursive version: def total_acc(items, acc=0): if not items: return acc; return total_acc(items[1:], acc + items[0]). Loop version: def total_loop(items): acc = 0; while True: if not items: return acc; items, acc = items[1:], acc + items[0]. Both return 8 for [3, 1, 4].
Exercise
The calls in is_even and is_odd from the Mutual Recursion chapter are tail calls. What happens to is_even(100000) in Scheme compared with CPython?
Show answer
Scheme guarantees proper tail calls, including calls between different functions, so it runs in constant stack space and returns #t. CPython creates a new frame for every call and raises RecursionError once the depth passes the recursion limit, which is about 1000 by default.