---
title: "Tail Call Optimization in Python"
date: 2020-10-11T20:46:54-04:00
draft: false
tags: ["Python"]
medium_enabled: true
---

In a standard recursive function, a new stack frame is created every time a recursive call is made. This can lead to bad memory performance and as a protective measure, some programming languages have a maximum stack frame limit. 

The following example is in Python:

```python
def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n-1)
```

```python
>>> factorial(1000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in factorial
  File "<stdin>", line 4, in factorial
  File "<stdin>", line 4, in factorial
  [Previous line repeated 995 more times]
  File "<stdin>", line 2, in factorial
RecursionError: maximum recursion depth exceeded in comparison
```

## Implementation

To get around this in Python, we need some sort of [trampoline](https://en.wikipedia.org/wiki/Tail_call#Through_trampolining), or way to exit part the stack and call the recursive function again. This technique is often used in Tail Call Optimization, and we can do this in Python using exceptions. This code is heavily inspired by Crutcher Dunnavant's [code snippet](https://code.activestate.com/recipes/474088-tail-call-optimization-decorator/) from 2006.

```python
"""
Python Decorator that enables tail call
optimization through Exception Trampolines.
"""
from dataclasses import dataclass, field
from typing import Any, Dict, List
import functools
import inspect

@dataclass
class TailRecurseException(Exception):
    """Exception to enable tail call recursion."""
    args: List[Any] = field(default_factory=list)
    kwargs: Dict[Any, Any] = field(default_factory=dict)

def tail_call(func):
    """
    Decorator that performs tail call optimization.

    Notes
    =====
    Works by throwing an exception to exit the stack
    when the function sees itself as its grandparent in
    the stack trace. It then calls itself with its new
    arguments.
    """
    @functools.wraps(func)
    def recurse(*args, **kwargs):
        frame = inspect.currentframe()
        if frame.f_back is not None \
           and frame.f_back.f_back is not None \
           and frame.f_back.f_back.f_code == frame.f_code:
            raise TailRecurseException(args, kwargs)
        while True:
            try:
                return func(*args, **kwargs)
            except TailRecurseException as exception:
                args = exception.args
                kwargs = exception.kwargs
    return recurse

```

## Example: Factorial

Now let's redefine `factorial` in a tail-call way:

```python
@tail_call
def factorial(n, acc=1):
    if n == 0:
        return acc
    return factorial(n - 1, n * acc)
```

For the moment of truth...

```python
>>> factorial(1000)
 

```

## Example: Fibonacci Numbers

```python
@tail_call
def fib(n, a=0, b=1):
    if n == 0:
        return a
    if n == 1:
        return b
    return fib(n - 1, b, a + b)
```

```python
>>> fib(1000)
43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875
```

## Conclusion

You can install the package via pypi:

```bash
pip install tail-recurse
```

It is also available on [Github](https://github.com/Brandon-Rozek/tail-recurse/).
